我强烈建议你看看异步库,它是处理这类事情的一个很好的库。
现在让我们谈谈您的问题以及如何解决。假设updatePE是您自己的函数,我会将该函数转换为承诺或向其添加回调,这样您就知道它何时完成执行。
例如
// Promise implementation
function updatePE(x, y, z) {
return new Promise(function(resolve, reject){
// Do your work here and when is done resolve it
resolve();
});
}
// Callback implementation
function update(x, y, z, callback)
{
// Do your work here and when is done, callback
callback()
}
现在使用异步库,您可以执行以下操作
// If your updatePE uses callback
async.forEach(result.rows, function(row, callback) {
updatePE(x, y, z, function() {
callback(null)
});
}, function(err){
if (err) {
// Loop is finished with an error
} else {
// Loop is finished without an error
}
});
// If your updatePE uses promise
async.forEach(result.rows, function(row, callback) {
updatePE(x, y, z)
.then(function(){
callback(null)
})
.catch(function(err){
callback(err)
})
}, function(err){
if (err) {
// Loop is finished with an error
} else {
// Loop is finished without an error
}
});