Can’t throw error from within an async promise executor function

This is the async/await version of the Promise constructor antipattern!

Never ever use an async function as a Promise executor function (even when you can make it work1)!

[1: by calling resolve and reject instead of using return and throw statements]

by “asynchronous” they’re not referring to async functions, so I don’t think their explanations apply here

They could as well. A simple example where it cannot work is

new Promise(async function() {
    await delay(…);
    throw new Error(…);
})

which is equivalent to

new Promise(function() {
    return delay(…).then(function() {
        throw new Error(…);
    });
})

where it’s clear now that the throw is inside an asynchronous callback.

The Promise constructor can only catch synchronous exceptions, and an async function never throws – it always returns a promise (which might get rejected though). And that return value is ignored, as the promise is waiting for resolve to be called.

Leave a Comment