Does await await promise-like objects? [duplicate]

Deadly 提交于 2019-12-30 08:33:22

问题


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

  1. obj is initialized
  2. setTimeout() is executed, its callback will be called in the next tick
  3. go() is declared
  4. go() is executed
  5. await is triggered inside go(), which executes obj.then(), assigning the resolving function to obj.func
  6. it has not been resolved yet so the tick ends here

Second tick

  1. setTimeout() callback is executed, resolving the promise through obj.func() with the value 57

Third tick

  1. the control is back to go(), and the result 57 is logged



回答2:


From that same page:

If the value is not a Promise, it converts the value to a resolved Promise, 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!