Is it an anti-pattern to use async/await inside of a new Promise() constructor?

I agree with the answers given above and still, sometimes it’s neater to have async inside your promise, especially if you want to chain several operations returning promises and avoid the then().then() hell. I would consider using something like this in that situation:

const operation1 = Promise.resolve(5)
const operation2 = Promise.resolve(15)
const publishResult = () => Promise.reject(`Can't publish`)

let p = new Promise((resolve, reject) => {
  (async () => {
    try {
      const op1 = await operation1;
      const op2 = await operation2;

      if (op2 == null) {
         throw new Error('Validation error');
      }

      const res = op1 + op2;
      const result = await publishResult(res);
      resolve(result)
    } catch (err) {
      reject(err)
    }
  })()
});

(async () => {
  await p;
})().catch(e => console.log("Caught: " + e));
  1. The function passed to Promise constructor is not async, so linters don’t show errors.
  2. All of the async functions can be called in sequential order using await.
  3. Custom errors can be added to validate the results of async operations
  4. The error is caught nicely eventually.

A drawback though is that you have to remember putting try/catch and attaching it to reject.

Leave a Comment