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

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

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

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

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;

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

拥抱异步性:

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;

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

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

代码如下:

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);
};