以下当前在 node、chrome、firefox 中记录 Yahtzee
。
如你所见,甚至连 Promise 的原型(prototype)都没有设置。
const fake = new Number(1)
fake.then = fn => setTimeout(fn, 0, 'Yahtzee')
const main = async () => {
console.log(await fake)
}
main()
这是否普遍适用?
更重要的是,这种行为可能会持续下去吗?
是的,这会起作用。 According to the specs ,将调用一个新的 Promise 并使用该值进行解析。 Promise.resolve
与 thenable 一起工作,因此它对 await
的工作方式相同
所以,上面的等价于
const fake = new Number(1)
fake.then = fn => setTimeout(fn, 0, 'Yahtzee')
const main = async () => {
console.log(await Promise.resolve(fake))
}
main()
在哪里the .resolve()
method that calls then
在对象上。