【问题标题】:How to wait for function to finish before continuning in Node.js如何在继续使用 Node.js 之前等待函数完成
【发布时间】:2015-03-04 08:40:21
【问题描述】:

我正在尝试在 Node.js/Express 中创建一个路由,该路由从两个查询中读取数据,然后根据来自 queires 的数据增加一个计数。由于 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;

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

【问题讨论】:

  • 你传递回调。事件发射器也可以工作。或者承诺。将问题视为必须“等待”直到完成某事是错误的。您宁愿将其视为“我如何知道 X 何时完成以运行 Y”。而回调、事件或承诺都是该问题的解决方案。

标签: javascript node.js asynchronous


【解决方案1】:

拥抱异步:

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;

或者使用 Promise 库,或者使用事件。最后,它们都是异步回调机制,语义略有不同。

【讨论】:

    【解决方案2】:

    你可以使用像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);
    };
    

    【讨论】:

      猜你喜欢
      • 2021-06-26
      • 2015-09-16
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多