0

Can anyone explain why the last example prints 42 instead of Promise { ... }?

let f = async function () { return 42; }
let g = async function () { return new Promise((resolve, reject) => resolve(42)); }

f()
-> Promise { ... }

await f()
-> 42

g()
-> Promise { ... }

await g()
-> 42

It seems like the promise created by async is somehow being merged with the promise created and returned inside g()?

elplatt
  • 3,227
  • 3
  • 18
  • 20
  • `await` doesn't create a promise. Also, you shouldn't return a promise from a async function. – tkausl Feb 10 '23 at 19:40
  • 3
    There is no such thing as a promise that resolves to a promise. They autoflatten. If you expect you'd need `await await f` that's never possible. – VLAZ Feb 10 '23 at 19:41
  • Promises are created automatically by `async`, not `await`. `await` is syntactic sugar for `.then()` – Barmar Feb 10 '23 at 19:44
  • @tkausl You are correct about async/await and I have updated my post. – elplatt Feb 10 '23 at 20:03
  • 2
    *"is somehow being merged with the promise"*: and that's one of the important features of promises. If a promise is resolved with a promise, the first promise is locked-in -- it will settle when the second promise settles, and with the same outcome. [EcmaScript2015 specs, 25.4 Promise Objects](https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects) – trincot Feb 10 '23 at 20:17

0 Answers0