Recently I have been having an issue with await
not waiting for a function to finish in a for ... of
loop. I seem to have poor understanding of what needs to be fulfilled for a await
to actually wait for a function to fully resolve. This is the code I'm looking at:
async function updateFromAllSources(){
try{
console.log(appLock)
if(appLock===1){
throw 'Application is currently running!'
}
appLock = 1;
const sources = await Source.find({}).exec();
for(const source of sources){
console.log(`[LOG] Updating ${source.name}`)
await updateProductsFromCsv(source)
}
appLock = 0;
} catch (e) {
console.log(`[LOG]${e}`)
}
}
async function updateProductsFromCsv(source){
try{
const {body} = await got.get(source.url, {
responseType: 'text',
});
let productActive = 0;
csv(body.trim(), { columns: true, delimiter: source.delimiter }, async (err, records) => {
for (const [index, element] of records.entries()) {
if (element['Stock'] > source.minStock) {
productActive = 1;
}
console.log(`[LOG] Aktualizacja produktu ${index}/${records.length}`);
io.emit('logging', `Aktualizacja produktu ${index}/${records.length}`);
await updateProductByName(element['Article number'], { stock: element['Stock'], active: productActive });
}
})
} catch(error){
console.error(error);
}
}
Now: await updateProductsFromCsv(source)
resolves immediately without waiting for the loop in updateProductsFromCsv()
, but the same construct used in updateProductsFromCsv()
where it's supposed to wait for updateProductByName()
works as expected, the loop waits for the function to be resolved before iterating further.
What's the difference? How do I make the first for loop wait for the function to resolve?