问题
According to Mozilla, await only awaits Promises:
[rv] Returns the resolved value of the promise, or the value itself if it's not a Promise.
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();
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.)
回答1:
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.
You have some information about that here.
In your case it works because:
First tick
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
Second tick
setTimeout()
callback is executed, resolving the promise throughobj.func()
with the value57
Third tick
- the control is back to
go()
, and the result57
is logged
回答2:
From that same page:
If the value is not a
Promise
, it converts the value to a resolvedPromise
, and waits for it.
The value will thus automatically be converted to a resolved Promise
, and then be waited for.
来源:https://stackoverflow.com/questions/45165365/does-await-await-promise-like-objects