如何等待功能的Node.js continuning前完成 [英] How to wait for function to finish before continuning in Node.js

查看:131
本文介绍了如何等待功能的Node.js continuning前完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创造的Node.js / EX preSS的路线,从两个查询中读取数据,然后递增的基础上从queires数据计数。自的Node.js是异步的所有数据已被读出之前被显示我的总。

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.

我创建了一个简单的例子,获取到的我目前做什么点

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?

推荐答案

拥抱异步性:

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.

这篇关于如何等待功能的Node.js continuning前完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆