Reputation: 1108
I wrote a piece of code inside an async function that shall create four users concurrently, save them to a MongoDB and print a message when this is done:
// Concurrently create dummy users
const dummyUserDict = [
"name1",
"name2",
"name3",
"name4"
];
const dummyUserPromises = dummyUserDict.map(async (name) => {
let user = new User({
_id: new mongoose.Types.ObjectId,
username: name
});
return user
.save()
.then((result) => {
console.log('Created user ' + result.username + '!');
});
});
try {
await Promise.all[dummyUserPromises];
} catch(e) {
console.log(e);
}
console.log('Stop here!');
I'd expect all dummyUserPromises
to be resolved when reaching the end of the code as I explicitly await
them with Promise.all
beforehand. When I turn on my debugger and set a breakpoint at console.log('Stop here!')
I find that they are all still pending:
Why is this?
Upvotes: 0
Views: 136
Reputation: 138277
You have to call the function:
await Promise.all(dummyUserPromises)
Using []
you try to access a property of the Promise.all
function, which will result in undefined
and await undefined
won't wait for anything.
Upvotes: 3