JavaScript承诺then()排序 [英] JavaScript Promise then() ordering
问题描述
我还在学习JavaScript 承诺
s,我遇到了一个我不理解的行为。
I'm still learning JavaScript Promise
s, and I came across a behavior I don't understand.
var o = $("#output");
var w = function(s) {
o.append(s + "<br />");
}
var p = Promise.resolve().then(function() {
w(0);
}).then(function() {
w(1);
});
p.then(function() {
w(2);
return new Promise(function(r) {
w(3);
r();
}).then(function() {
w(4);
});
}).then(function() {
w(5);
});
p.then(function() {
w(6);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
我希望这些语句按顺序运行 - 也就是说,那个输出将是
I would expect these statements to run in order--that is, the that output would be
0
1
2
3
4
5
6
相反,输出是
0
1
2
3
6
4
5
甚至删除内部的承诺
给出了我认为与之相矛盾的结果。 1
在 2
之前输出,但 6
之前输出 5
。
Even removing the inner Promise
gives, what seems to me to be, contradicting results. 1
is output before 2
, but 6
is output before 5
.
有人可以向我解释一下吗?
Can someone explain this to me?
我注意到的是每次重新分配 p
给我们预期的订单。
Something I have noticed is that reassigning p
each time gives us the order I would expect.
推荐答案
你早期看到 6
的原因是因为你没有链,你分支了。
The reason you see 6
early is because you didn't chain, you branched.
当你打电话给 p.then()。then()。then()
时,你有一个必须以正确的顺序执行的承诺链。
但是,如果你调用 p.then()。then(); p.then()
,你有2个承诺附加到 p
- 基本上创建一个分支,第二个分支将随之执行第一。
When you call p.then().then().then()
, you've got a chain of promises that must execute in the correct order.
However, if you call p.then().then(); p.then()
, you've got 2 promises attached to p
- essentially creating a branch, and the 2nd branch will execute along with the first.
您可以通过确保将它们链接在一起来解决这个问题 p = p.then()。then(); p.then();
You can fix this by ensuring you chain them together p = p.then().then(); p.then();
仅供参考,你几乎不想分支,除非你把它们重新组合在一起(例如。 Promise.all
),或者故意创建即发即弃分支。
FYI, you almost NEVER want to branch, unless you bring them back together (eg. Promise.all
), or are intentionally creating a "fire and forget" branch.
这篇关于JavaScript承诺then()排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!