skip to Main Content

Consider the following assignments:

const promise1 = (async () => {
    await someAsyncFunction();
})();

const promise2 = new Promise(async resolve => {
    await someAsyncFunction();
    resolve();
});

Is there any meaningful difference between these two Promises (other than verbosity)?

2

Answers


  1. Chosen as BEST ANSWER

    Consider the following definition of someAsyncFunction:

    async function someAsyncFunction() {
        throw "Error in someAsyncFunction!";
    }
    

    In this case, both promise 1 and promise 2 cause an unhandled rejection error. But afterwards, the two promises are in different states. Promise 1 (defined using the async IIFE) has rejected with the reason "Error in someAsyncFunction!" but promise 2 is still pending. This behavior was confirmed in NodeJS and Firefox.


  2. They’re basically the same, the IIFE is syntactic sugar for the 2nd version

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search