function runAll(){
for (var i = 0; i < Math.random(); i++) {
pool.connect(function(err, client, done) {
client.query("update box set gamer_id=null where box_id=$1; ", [i], function(err, resultUpdate) {
if(err)
return "has error"
//when all query finished then return value
return "finished all query";
})
})
}
return "after for";
}
此函数一直返回“after for”但我希望当所有查询完成后返回“完成所有查询”,因为这些查询可能有一些错误。
如何在所有查询完成后返回值?
我不能使用pg-promise ...
答案 0 :(得分:1)
试试这个,
function runAll(cb){
var total = Math.random()
for (var i = 0; i < total; i++) {
pool.connect(function(err, client, done) {
client.query("update box set gamer_id=null where box_id=$1; ", [i], function(err, resultUpdate) {
i==total-1 && cb(err, resultUpdate)
})
})
}
}
console.log("before invoke of runAll")
console.time("dbprocess");
runAll(function allDone(err, res){
console.log("after call of runAll completed");
console.timeEnd("dbprocess");
if(err)
return "has error"
//when all query finished then return value
return "finished all query";
})
console.log("after invoke of runAll")
另见JS中的计时器,https://stackoverflow.com/a/18427652/4466350
我觉得你不需要关于回调的解释,但我可能有错,请告诉我们。