[英]How to wait for function to finish before continuning in 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. 我正在尝试在Node.js / Express中创建一个路径,该路由从两个查询中读取数据,然后根据来自queires的数据递增计数。 Since Node.js is asynchronous my total is displayed before all the data has been read.
由于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?
我是否必须创建一个自定义事件发射器才能实现此目的?
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. 或使用promises库,或使用事件。 In the end, they're all asynchronous callback mechanisms with slightly different semantics.
最后,它们都是具有略微不同语义的异步回调机制。
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);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.