I have a async map function but want it to execute synchronously because I need the output of the first statement to be used within the same loop. But the map runs asynchronously even with await statements, can you please help understand why this happens.
My use case if to insert a record into mongodb if not present and update it if present in a loop. The data exists in the db but find fails within the loop but works outside.
My code:
const doSomethingAsync = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve(Date.now());
}, 1000);
});
};
await Promise.all(
modelVarients.map(async varient => {
console.log(`varient: ${varient._id}`);
console.log('1');
const onlineDevice = await Device.findOne({
model: varient._id,
});
console.log('2');
await doSomethingAsync();
console.log('3');
await doSomethingAsync();
console.log(JSON.stringify(onlineDevice));
await doSomethingAsync();
console.log('4');
return varient;
})
);
Logs I get:
varient: 8 pro
1
varient: note
1
varient: iphone x
1
2
2
2
3
3
3
null
null
null
4
4
4
But what I expect to get:
varient: 8 pro
1
2
3
<actual response from db for 8 pro>
4
varient: note
1
2
3
<actual response from db for note>
4
varient: iphone x
1
2
3
<actual response from db for iphone x>
4