如何在Node.js中连接之前等待函数完成

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

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

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; 

我不知道为了等到两个function都完成之后我才能打印总数。 我需要创build一个自定义的事件发射器来实现这个吗?

拥抱asynchronous性:

 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; 

或使用承诺库,或使用事件。 最后,它们都是asynchronouscallback机制,语义略有不同。

你可以使用一些库,如asynchronous 。

这里是代码:

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