简体   繁体   English

使用本机(ES6)JavaScript承诺“等待”承诺或常规对象

[英]“Waiting” on either a promise or regular object using native(ES6) JavaScript promises

I played with promises a few times a few years ago using either jQuery or Q. I'm now quite rusty and want to learn and use the new native ES6 promises. 几年前,我使用jQuery或Q玩过Promise。我现在很生锈,想学习和使用新的原生ES6 Promise。

I seem to remember one neat concept where you can "wait" on something and not care whether it's a plain object or a promise. 我似乎记得一个简洁的概念,您可以在其中“等待”某物,而不在乎它是简单的对象还是承诺。 If it's a promise the callback is called when it asynchronously completes, if it's anything else the callback is called immediately - maybe the next tick. 如果它是一个承诺,则在异步完成时将调用该回调,否则,将立即调用该回调-可能是下一个刻度。

But I can't recall how this is done. 但是我不记得是怎么做到的。 I'm not sure if it has a name so it's proving difficult to Google for. 我不确定它是否有名称,因此对于Google来说很难。 I'm not sure if it's a standard feature across all JS promise implementations, or if it was just something only jQuery had. 我不确定这是否是所有JS promise实现中的标准功能,还是仅仅是jQuery所具有的功能。

What is this called? 这个叫什么? Can I still do this with native promises? 我仍然可以使用本地承诺吗? Where can I read up on it? 在哪里可以阅读?

Both jQuery's $.when() and ES6's Promise.all() exhibit the behaviour you refer to. jQuery的$.when() Promise.all() $.when()和ES6的Promise.all()展现了您所引用的行为。 Provide a promise and the function waits for the promise to resolve, but for any other value it returns immediately. 提供一个promise,函数等待该promise解析,但是对于其他任何值,它将立即返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM