Promise 回调以什么顺序触发? [英] In what order are Promise callbacks triggered?

查看:44
本文介绍了Promise 回调以什么顺序触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说已经执行了以下语句,按顺序:

Say the following statements have been executed, in this order:

promiseA.then(function() { console.log('A1'); });
promiseB.then(function() { console.log('B'); });
promiseA.then(function() { console.log('A2'); });

现在 promiseA 已满 接着 promiseB.

它是否在规范中定义(是this 最新的规范?)三个回调的触发顺序是什么?

Is it defined in the spec (is this the latest spec?) in which order the three callbacks are triggered?

A1 是否总是在 A2 之前触发?(更新:是的,根据 本规范 中的 2.2.6.1,正如 这个答案.)

Will A1 always be triggered before A2? (Update: Yes, per 2.2.6.1 from this spec, as pointed to from this answer.)

A1/A2 是否总是在 B 之前触发(因为 A 在 B 之前完成)?

Will A1/A2 always be triggered before B (since A was fulfilled before B)?

推荐答案

A1/A2 是否总是在 B 之前触发(因为 A 在 B 之前完成)?

Will A1/A2 always be triggered before B (since A was fulfilled before B)?

不,不一定.回调的顺序仅按承诺定义.甚至有可能在 A1 和 A2 之间触发 B.

No, not necessarily. The order of callbacks is only defined per promise. It might even happen that B is triggered between A1 and A2.

无论如何这都没有实际意义,因为通常您不知道promiseApromiseB 之前得到满足.当 promiseB 派生自 promiseA 时,您只能依赖它 - 然后保证在 A 上的派生回调"导致 B 之后调用 B 的回调.

This doesn't really make sense anyway, as usually you don't know that promiseA is fulfilled before promiseB. You could only rely on that when promiseB was derived from promiseA - then callbacks for B are guaranteed to be called after the "derivation callback" on A that led to B.

所以,如果你需要保证回调只在 A1 和 A2 之后发出(因为它依赖于它们的结果),你应该这样做

So, if you need to guarantee that a callback is only issued after A1 and A2 (because it relies on their results), you should be doing

var promiseA1 = promiseA.then(function(a) { console.log('A1'); return 'A1'; });
var promiseA2 = promiseA.then(function(a) { console.log('A2'); return 'A2'; });
Promise.all([promiseB, promiseA1, promiseA2]).spread(function(b, a1, a2) {
    console.log('B after ', a1, a2);
});

这篇关于Promise 回调以什么顺序触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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