1
async function pending() { 
  return new Promise((resolve, reject) => { resolve(1) });
}

async function fulfilled() {
  return 1;
}

function promiseState(p) {
   return Promise.race([ Promise.resolve(p).then(() => "fulfilled", () => "rejected"), Promise.resolve().then(() => "pending") ]);
}

promiseState(pending()).then(s => { console.log(s); });        // pending
promiseState(fulfilled()).then(s => { console.log(s); });      // fulfilled

pending().then(r => { console.log(r); });        // 1
fulfilled().then(r => { console.log(r); });      // 1

What's different?

When should I use 'return new Promise(...' in async function? and Why?

2 Answers2

1

It's the same as the difference between

function pending() { 
  return Promise.resolve(Promise.resolve(1));
}

and

function fulfilled() {
  return Promise.resolve(1);
}

The former just takes one promise tick longer to settle.

When should I use 'return new Promise(...' in async function?

Probably never. See How to turn this callback into a promise using async/await? and What is the benefit of prepending async to a function that returns a promise?.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

You should not construct Promises explicitly inside another Promise or async function, thats the promise constructor antipattern. It just adds additional overhead and you get no benefit whatsoever. If you somewhen really need the Promise constructor (for wrapping a callback API), then the surounding function should not be async, just return the promise.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151