Below is my async function to read values from DB and logs something on console. But for some reason its not happening.
So, I create an array of promises and then keep waiting for all promises to resolve as promises will read from DB. But await on Promise.all is not pausing the execution of code and not waiting for all promises to resolve instead its passing control back to calling function. Is there anything I am missing here ?
async function readValuesFromDB(codes) {
console.log('trying to read values from DB');
let dbPromises = [];
for(let code in codes) {
let refId = 'some_random_reference_id_generated_from_codes[i]';
dbPromises.push(MyDb.getPromise(refId)); // getPromise() returns a promise that reads from DB
}
console.log('waiting for all promises to resolve...');
// waiting for all promises to finish
await Promise.all(dbPromises).then((allPromises) => {
for(let i in allPromises) {
console.log('OK..read from DB');
}
});
console.log('all promises resolved');
}
console.log('calling readValuesFromDB()');
readValuesFromDB();
console.log('finished readValuesFromDB()');
Output from above call is:
trying to read values from DB
waiting for all promises to resolve...
finished readValuesFromDB
......
......
OK..read from DB
OK..read from DB
OK..read from DB
...
...
all promises resolved
Ideally output should be below (since I am waiting for all promises to resolve using await with Promise.all)
trying to read values from DB
waiting for all promises to resolve...
OK..read from DB
OK..read from DB
OK..read from DB
...
...
So looks like promises are getting resolved after the control is passed back to calling function and seems like await has no effect here.
Any help on why await is not in effect in this case ?