如何确保循环完成后声明中得到执行? [英] How to ensure that a statement gets executed after a loop completes?
问题描述
下面是我的code从路由/ index.js快照
exports.index =功能(REQ,RES){
VAR的结果=新的Array();
对于(VAR I = 0; I< 1000;我++){
//做数据库查询或在这里的时间密集型任务的基础上我
//每个结果添加到结果数组
}
res.render('指数',{名称:,结果:结果'家!'});
};
如果我运行这个code,由于异步性质的JavaScript前循环得到完全处理的最后一行被执行。因此,我的网页可是没有结果。如何构建这种这样的方式在页面被加载,一旦查询完成?
更新
里面的循环我有数据库code(Redis的),如下面的 -
client.hgetall(游戏:+ I,功能(ERR,回复){ results.push(reply.name);
});
exports.index =功能(REQ,RES){
VAR的事件=要求(事件);
变种E =新events.EventEmitter();
e.expected = 1000;
e.finished = 0;
e.results = []; E.ON公司(finishedQuery(功能(ERR,R){
this.finished + = 1;
this.results.push(R&放大器;&放大器; r.name);
如果(this.finished === this.expected){
res.render('指数',{名称:,结果:this.results'家!'});
};
})绑定(e)条); 对于(VAR I = 0; I< e.expected;我++){
client.hgetall(游戏:+ I,功能(ERR,回复){
e.emit(finishedQuery,呃,回复)
});
};
};
当然,上面的code不处理[1或更多]错误。你需要在第一个错误或(2)如果没有发生错误添加逻辑,只有响应(1)。
Below is a snapshot of my code from 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 });
};
If I run this code , due to the asynchronous nature of javascript the last line gets executed before the loop gets completely processed . Hence my webpage doesnt have the results . How do I structure this such a way that the page gets loaded once the queries are completed ?
Updated
Inside the loop I have database code ( Redis ) like the below -
client.hgetall("game:" +i, function(err, reply) {
results.push(reply.name);
});
exports.index = function(req, res) {
var events = require("events");
var e = new events.EventEmitter();
e.expected = 1000;
e.finished = 0;
e.results = [];
e.on("finishedQuery", (function(err, r) {
this.finished += 1;
this.results.push(r && r.name);
if (this.finished === this.expected) {
res.render('index', { title: 'Home !' , results:this.results });
};
}).bind(e));
for (var i = 0; i < e.expected; i++) {
client.hgetall("game:" + i, function(err, reply) {
e.emit("finishedQuery", err, reply);
});
};
};
Of course, the above code doesn't handle [1 or more] errors. You'd need to add logic that only responds (1) on the first error or (2) if no errors occur.
这篇关于如何确保循环完成后声明中得到执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!