为什么Promise库使用事件循环? [英] Why do Promise libraries use event loops?

查看:72
本文介绍了为什么Promise库使用事件循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下JavaScript代码:

Considering the following JavaScript code:

var promise = new Promise();
setTimeout(function() {
    promise.resolve();
}, 10);

function foo() { }
promise.then(foo);

在我见过的promise实现中,promise.resolve()只是设置一些属性来表示承诺已解决,并且在事件循环中稍后会调用foo(),但似乎promise.resolve()会具有足够的信息,可以立即调用任何延迟函数,例如foo()。

In the promise implementations I've seen, promise.resolve() would simply set some property to indicate the promise was resolved and foo() would be called later during an event loop, yet it seems like the promise.resolve() would have enough information to immediately call any deferred functions such as foo().

事件循环方法似乎会增加复杂性并降低性能,所以为什么要使用它?

The event loop method seems like it would add complexity and reduce performance, so why is it used?

虽然我大部分使用诺言使用JavaScript,我的问题的部分原因是在性能非常高的情况下(例如C ++游戏)实现promise,在这种情况下,我想知道是否可以在没有事件循环开销的情况下利用promise的某些好处。 / p>

While most of my use of promises is with JavaScript, part of the reason for my question is in implementing promises in very performance intensive cases like C++ games, in which case I'm wondering if I could utilize some of the benefits of promises without the overhead of an event loop.

推荐答案

所有promise实现,至少是好的实现。

All promise implementations, at least good ones do that.

这是因为将同步混合到异步API中是

This is because mixing synchronicity into an asynchronous API is releasing Zalgo.

事实承诺有时并不会立即解决,有时会推迟意味着API是一致的。否则,您将按执行顺序获得未定义的行为。

The fact promises do not resolve immediately sometimes and defer sometimes means that the API is consistent. Otherwise, you get undefined behavior in the order of execution.

function getFromCache(){
      return Promise.resolve(cachedValue || getFromWebAndCache());
}

getFromCache().then(function(x){
     alert("World");
});
alert("Hello");

事实承诺库会延迟执行,这意味着可以保证上述代码块的执行顺序。在像jQuery这样的承诺承诺实现中,顺序会根据是否从缓存中获取项目而改变。这很危险。

The fact promise libraries defer, means that the order of execution of the above block is guaranteed. In broken promise implementations like jQuery, the order changes depending on whether or not the item is fetched from the cache or not. This is dangerous.

具有不确定的执行顺序是非常危险的,并且是错误的常见来源。 Promises / A +规范将您带入成功之路。

Having nondeterministic execution order is very risky and is a common source of bugs. The Promises/A+ specification is throwing you into the pit of success here.

这篇关于为什么Promise库使用事件循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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