[英]How to wait for function to finish before continuning in Node.js
我正在嘗試在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;
我不確定在打印總數之前要等到兩個功能都完成后我要做什么。 我是否必須創建一個自定義事件發射器才能實現此目的?
擁抱異步性:
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);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.