为什么 Promise 库使用事件循环?

2021-12-29 00:00:00 performance javascript c++ promise

考虑以下 JavaScript 代码:

var promise = new Promise();设置超时(功能(){承诺.resolve();}, 10);函数 foo() { }承诺.then(foo);

在我见过的承诺实现中,promise.resolve() 会简单地设置一些属性来指示承诺已解决,并且稍后将在事件循环中调用 foo(),但它看起来像 promise.resolve() 将有足够的信息来立即调用任何延迟函数,例如 foo().

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

虽然我对 Promise 的大部分使用是与 JavaScript 一起使用的,但我提出问题的部分原因是在 C++ 游戏等性能非常密集的情况下实现 Promise,在这种情况下,我想知道是否可以利用没有事件循环开销的承诺.

解决方案

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

这是因为将同步性混合到异步 API 中是发布 Zalgo.>

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

function getFromCache(){返回 Promise.resolve(cachedValue || getFromWebAndCache());}getFromCache().then(function(x){警报(世界");});警报(你好");

fact promise libraries defer,意味着上面块的执行顺序是有保证的.在像 jQuery 这样的违背承诺的实现中,顺序会根据项目是否从缓存中获取而改变.这很危险.

具有不确定的执行顺序是非常危险的,并且是错误的常见来源.Promises/A+ 规范把你扔进了成功的坑里.

Considering the following JavaScript code:

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

function foo() { }
promise.then(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?

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.

解决方案

All promise implementations, at least good ones do that.

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

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");

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.

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.

相关文章