等待是否在等待诺言样的对象? [英] Does await await promise-like objects?

查看:81
本文介绍了等待是否在等待诺言样的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 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:

第一次打勾

  1. obj已初始化
  2. setTimeout()被执行,其回调将在下一个时钟周期被调用
  3. go()被声明
  4. go()被执行
  5. awaitgo()内部触发,执行obj.then(),将解析功能分配给obj.func
  6. 它尚未解决,所以刻度在这里结束
  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

第二勾

    执行
  1. setTimeout()回调,通过obj.func()解析值为57
  2. 的承诺
  1. setTimeout() callback is executed, resolving the promise through obj.func() with the value 57

第三个刻度

  1. 控件返回到go(),并记录结果57
  1. the control is back to go(), and the result 57 is logged

这篇关于等待是否在等待诺言样的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆