如何确保在循环完成后执行语句?

gee*_*ter 3 javascript asynchronous node.js express

下面是来自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 });
};
Run Code Online (Sandbox Code Playgroud)

如果我运行此代码,由于javascript的异步性质,最后一行在循环完全处理之前执行.因此我的网页没有结果.我如何构建这样一种方式,一旦查询完成页面加载?


更新

在循环内部我有数据库代码(Redis),如下所示 -

client.hgetall("game:" +i, function(err, reply) {

           results.push(reply.name);
        });
Run Code Online (Sandbox Code Playgroud)

glo*_*tho 6

使用异步库:

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 });
    });
};
Run Code Online (Sandbox Code Playgroud)

如果循环中的一个任务是异步的,则需要向异步任务传递一个调用的回调callback().如果您没有要使用的数组forEach,只需使用整数1-1000填充一个数组.

编辑:鉴于您的最新代码,只需在async callback()之后responses.push(reply.name).