下面是我在 routes/index.js 中的代码快照
exports.index = function(req, res){
var results=new Array();
for(var i=0; i<1000;i++){
//do database query or time intensive task here based on i
// add each result to the results array
}
res.render('index', { title: 'Home !' , results:results });
};
如果我运行这段代码,由于 javascript 的异步特性,最后一行在循环得到完全处理之前得到执行。因此我的网页没有结果。我如何构建这种方式,以便在查询完成后加载页面?
已更新
在循环中,我有如下所示的数据库代码 (Redis) -
client.hgetall("game:" +i, function(err, reply) {
results.push(reply.name);
});
最佳答案
使用 async library :
exports.index = function(req, res){
var results=new Array();
async.forEach(someArray, function(item, callback){
// call this callback when any asynchronous processing is done and
// this iteration of the loop can be considered complete
callback();
// function to run after loop has completed
}, function(err) {
if ( !err) res.render('index', { title: 'Home !' , results:results });
});
};
如果循环中的任务之一是异步的,您需要向异步任务传递一个调用 callback()
的回调。如果您没有要在 forEach
中使用的数组,只需用 1-1000 的整数填充一个即可。
编辑:根据您的最新代码,只需将 async
callback()
放在 responses.push(reply.name )
。
关于javascript - 如何确保在循环完成后执行语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13907495/