I highly recommend you take a look at the async library, it is a great library for this sort of things.
Now lets talk about your issue and how can it be solved. assuming updatePE
is your own function I would convert that function to a promise or add a callback to it, this way you know when it finishes executing.
for example
// 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()
}
now using the async library you can do the following
// 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
}
});