"Promise fires on the same turn of the event loop" 是什么意思?

What does "Promise fires on the same turn of the event loop" mean?

NodeJS 新手。通过 promise 教程 ('promise-it-wont-hurt') 我有以下脚本:

var Q = require('q');
var deferred = Q.defer();
deffered.resolve('SECOND');
deffered.promise.then(console.log);
console.log('FIRST');

输出:

FIRST
SECOND

我不明白,我原以为既然 resolved 是先触发的,我应该先看 second。

他们解释说这是因为 'Promise fires on the same turn of the event loop'。我不明白那是什么意思...

基本上,重点是承诺的 then 处理程序将 不会 运行 在当前代码流完成执行并将控制权返回给之前执行环境(在本例中为 Node)。

这是 Promises/A+ 合规承诺的一个重要特征,因为它确保了可预测性。不管承诺是否立即解决:

function getAPromise() {
    var Q = require('q');
    var deferred = Q.defer();
    deferred.resolve('SECOND');
    return deferred.promise;
}

getAPromise().then(console.log);

console.log('FIRST');

或者10秒后是否解决:

function getAPromise() {
    var Q = require('q');
    var deferred = Q.defer();
    setTimeout(function () {
        deferred.resolve('SECOND');
    }, 10000);
    return deferred.promise;
}

getAPromise().then(console.log);

console.log('FIRST');

您可以放心,FIRST 将始终先记录。

这在 You don't know JS - async & performance 的第 2 章和第 3 章中进行了详细讨论。 sometimes 运行异步和sometimes运行同步的异步操作称为Zalgos,它们不被认为是一个好东西。

重要的是要注意 jQuery 中广泛使用的承诺不 遵守此行为并且也有 number of other problems。如果您发现自己有 jQuery 承诺,请将其包装在适当的承诺中并继续:

Q($.ajax(...)).then(breatheWithEase);

They explain that this happens because of 'Promise fires on the same turn of the event loop'. I don't understand what that means...

我也是,恕我直言,这部分没有多大意义。大概意思应该是当你调用resolve或者reject的时候,promise是立即settled的,以后不会再改变它的状态了。这与回调无关。

更重要的是要理解该段中的下一句话:

You can expect that the functions passed to the "then" method of a promise will be called on the NEXT turn of the event loop.

这就像一条简单的经验法则:then 回调总是 异步调用。始终,在每一个适当的承诺执行中;这是 Promises/A+ specification.

规定的

这是为什么?为了一致性。与您的示例片段不同,您不知道如何或何时解决承诺 - 您只是从您调用的某种方法中将其交还给您。它可能已经解决,也可能仍然悬而未决。现在你调用promise的then方法,你就可以知道:它会是异步的。您不需要处理 might be synchronous or not 的情况并更改代码的含义,它总是异步的。