Search code examples
javascriptasync-awaites6-promise

Does every ECMAScript runtime with await await any Thenable?


The following currently logs Yahtzee in node, chrome, firefox.

As you can see, not even prototype of Promise was set.

const fake = new Number(1)
fake.then = fn => setTimeout(fn, 0, 'Yahtzee')
const main = async () => {
  console.log(await fake)
}
main()

Does this works universally? And more importantly, will this behavior likely persist?


Solution

  • Yes, this will work. According to the specs, a new Promise will be called and resolve with that value. Promise.resolve works with thenable so it will work the same for await

    So, the above is equivalent to

    const fake = new Number(1)
    fake.then = fn => setTimeout(fn, 0, 'Yahtzee')
    const main = async () => {
      console.log(await Promise.resolve(fake))
    }
    main()
    

    Where it is the .resolve() method that calls then on the object.