303
303

Reputation: 1108

Why does this `Promise.all()` statement not wait for the promises to resolve?

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:

enter image description here

Why is this?

Upvotes: 0

Views: 136

Answers (1)

Jonas Wilms
Jonas Wilms

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

Related Questions