等待是否在等待诺言样的对象? [英] Does await await promise-like objects?
问题描述
根据 Mozilla ,仅等待等待承诺:
According to Mozilla, await only awaits Promises:
[rv]返回Promise的已解析值,如果不是Promise,则返回值本身.
[rv] Returns the resolved value of the promise, or the value itself if it's not a Promise.
如果您等待非承诺,那么将立即返回已解决的承诺,并且不会等待.但是,下面的代码将在不使用Chrome& amp;中使用Promises的情况下等待. FF.
If you await a non-Promise, a resolved promise will be immediately returned, and it will not await. However, the following code awaits without using Promises in Chrome & FF.
var obj = {
then:func => obj.func=func
};
setTimeout(() => obj.func(57), 1000);
async function go() {
var res = await obj;
console.log(res); //shows '57' after 1000ms
}
go();
根据规范,应该等待不是Promises的类似诺言的对象吗? (我尝试查看规格(与Mozilla文章链接),但我听不懂.)
According to the specs, should await await promise-like objects that are not Promises? (I tried looking at the specs (linked from the Mozilla article), but I couldn't understand it.)
推荐答案
await
将触发obj.then()
,这将导致该行为.因为即使obj
不是Promise,它也是 thenable对象.
await
is going to trigger obj.then()
, and that's causing that behavior. Because even if obj
is not a Promise, is a thenable object.
您在此处有一些信息.
在您的情况下,它的工作原理是:
In your case it works because:
第一次打勾
-
obj
已初始化 -
setTimeout()
被执行,其回调将在下一个时钟周期被调用 -
go()
被声明 -
go()
被执行 -
await
在go()
内部触发,执行obj.then()
,将解析功能分配给obj.func
- 它尚未解决,所以刻度在这里结束
obj
is initializedsetTimeout()
is executed, its callback will be called in the next tickgo()
is declaredgo()
is executedawait
is triggered insidego()
, which executesobj.then()
, assigning the resolving function toobj.func
- it has not been resolved yet so the tick ends here
第二勾
-
执行
-
setTimeout()
回调,通过obj.func()
解析值为57
的承诺
setTimeout()
callback is executed, resolving the promise throughobj.func()
with the value57
第三个刻度
- 控件返回到
go()
,并记录结果57
- the control is back to
go()
, and the result57
is logged
这篇关于等待是否在等待诺言样的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!