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

时间:2021-08-28 01:21:29

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玩过几次承诺。我现在很生疏,想要学习和使用新的原生ES6承诺。

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.

我似乎记得一个简洁的概念,你可以“等待”某些东西而不关心它是一个普通的对象还是一个承诺。如果它是一个承诺,当它异步完成时调用回调,如果它是其他任何东西,立即调用回调 - 也许是下一个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. 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?

这个叫什么?我还能用本机承诺做到这一点吗?我在哪里可以阅读它?

1 个解决方案

#1


2  

Both jQuery's $.when() and ES6's Promise.all() exhibit the behaviour you refer to. Provide a promise and the function waits for the promise to resolve, but for any other value it returns immediately.

jQuery的$ .when()和ES6的Promise.all()都展示了你引用的行为。提供承诺并且函数等待承诺解决,但对于任何其他值,它立即返回。

#1


2  

Both jQuery's $.when() and ES6's Promise.all() exhibit the behaviour you refer to. Provide a promise and the function waits for the promise to resolve, but for any other value it returns immediately.

jQuery的$ .when()和ES6的Promise.all()都展示了你引用的行为。提供承诺并且函数等待承诺解决,但对于任何其他值,它立即返回。