问题
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
回答1:
The modelVarients.map(async () => >...)
converts all the elements into Promises, which means they all start executing. Then the Promise.all()
collects them and waits for all of them, that's why you can use this structure to wait for the map
to finish. This is parallel processing.
What you need is sequential processing, which you can do with a reduce
, like this:
await modelVarients.reduce(async (memo, varient) => {
await memo;
// all the other things
}, Promise.resolve())
reduce
is similar to map
in a sense that it creates a Promise for all the elements in the array, but there is a current value that is passed from one element to the other. In this case, it is the Promise.resolve()
for the first one, the result of the first for the second, and so on. With the await memo
you can wait for the previous result.
With reduce
, the last element will wait for the previous one, which waits for the previous one, and so on, so there is no need for a Promise.all.
I've written articles about how map and reduce works with async functions, they will help you see the big picture.
回答2:
looks like You should chain Your promises, not running then in parallel with Promise.all
来源:https://stackoverflow.com/questions/63754451/how-to-synchronize-an-async-map-function-in-javascript