Search code examples
javascriptecmascript-6promisees6-promise

Is the resolve function necessary for promise constructor?


Consider the following promise array

const promiseArray = [1, 2, 3].map(num =>
  new Promise(async resolve => {
    while (num > 0) {
      await foo();
      num--;
    }
    await bar(num);
    resolve(); // No value to return
  })
);
const a = Promise.all(promiseArray);

Is the resolve function necessary?

Can we omit it and turn the promise into something like this?

const promiseArray = [1, 2, 3].map(num =>
  new Promise(async () => {
    while (num > 0) {
      await foo();
      num--;
    }
    await bar(num);
  })
);
const a = Promise.all(promiseArray);

Solution

  • Can we omit it and turn the promise into something like this?

    No, you cannot. Without calling resolve(), your new Promise() will never resolve. When you then call:

    const a = Promise.all(promiseArray);
    

    None of the promises in promiseArray will ever resolve. So, the promise a will never resolve. So, none of this will be of any use and you will have no way of knowing when everything is done executing.

    It doesn't appear you really need to wrap anything in a promise here. You can just do this:

    async function runLoop() {
        for (let i = 1; i <= 3; i++) {
            let num = i;
            while (num > 0) {
              await foo();
              num--;
            }
            await bar(num);    // note this will always be bar(0)
        }
    }
    
    runLoop().then(() => {
        console.log("all done");
    }).catch(err => {
        console.log(err);
    });
    

    Or, if you want your separate loops to run in parallel, you can do this:

    const promiseArray = [1, 2, 3].map(async num => {
      while (num > 0) {
        await foo();
        num--;
      }
      await bar(num);    // note this will always be bar(0)
    });
    Promise.all(promiseArray).then(() => {
        console.log("all done");
    }).catch(err => {
        console.log(err);
    });