Javascript 如何在 Node.js 中继续之前等待函数完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28849900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:29:59  来源:igfitidea点击:

How to wait for function to finish before continuning in Node.js

javascriptnode.jsasynchronous

提问by dfann

I am trying to create a route in Node.js/Express that reads data from two queries and then increments a count based on that data from the queires. Since Node.js is asynchronous my total is displayed before all the data has been read.

我正在尝试在 Node.js/Express 中创建一个路由,该路由从两个查询中读取数据,然后根据来自 queires 的数据递增计数。由于 Node.js 是异步的,所以我的总数在读取所有数据之前显示。

I created a simple example that gets to the point of what I am currently doing

我创建了一个简单的例子来说明我目前正在做的事情

var express = require('express');
var router = express.Router();


var total = 0;

/* GET home page. */
router.get('/', function(req, res, next) {
  increment(3);
  increment(2);
  console.log(total);
  res.end();
});



var increment = function(n){
    //Wait for n seconds before incrementing total n times
    setTimeout(function(){
    for(i = 0; i < n; i++){
        total++;
    }   
    }, n *1000);
};
module.exports = router;

I'm not sure what I would have to do in order to wait until both functions finish before I print the total. Would I have to create a custom Event Emitter to achieve this?

我不确定我必须做什么才能等到两个函数都完成后再打印总数。我是否必须创建一个自定义事件发射器来实现这一点?

回答by T.J. Crowder

Embrace asynchronicity:

拥抱异步性:

var express = require('express');
var router = express.Router();


var total = 0;

/* GET home page. */
router.get('/', function(req, res, next) {
  increment(3, function() {                 // <=== Use callbacks
      increment(2, function() {
          console.log(total);
          res.end();
      });
  });
});



var increment = function(n, callback){    // <=== Accept callback
    //Wait for n seconds before incrementing total n times
    setTimeout(function(){
        for(i = 0; i < n; i++){
            total++;
        }   
        callback();                        // <=== Call callback
    }, n *1000);
};
module.exports = router;

Or use a promises library, or use events. In the end, they're all asynchronous callback mechanisms with slightly different semantics.

或者使用承诺库,或者使用事件。归根结底,它们都是异步回调机制,语义略有不同。

回答by BlackMamba

You can use some library like async.

您可以使用一些库,例如async

Here is the code:

这是代码:

var total = 0;
/* GET users listing. */
router.get('/', function(req, res) {
    async.series([
            function(callback){
                increment(2, function(){
                    callback(null, "done");
                });
            },
            function(callback){
                increment(3, function(){
                    callback(null, "done");
                });
            }
        ],
        function(err, result){
            console.log(total);
            res.send('respond the result:' + total);
        });
});

var increment = function(n, callback){
    //Wait for n seconds before incrementing total n times
    setTimeout(function(){
        for(var i = 0; i < n; i++){
            total++;
        }
        callback();
    }, n *1000);
};