JavaScript Promise then() 排序 [英] JavaScript Promise then() ordering

查看:24
本文介绍了JavaScript Promise then() 排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在学习 JavaScript Promises,我遇到了一个我不理解的行为.

var o = $("#output");var w = 函数{o.append(s + "
");}var p = Promise.resolve().then(function() {w(0);}).那么(函数(){w(1);});p.then(function() {w(2);返回新的承诺(函数(r){w(3);r();}).那么(函数(){w(4);});}).那么(函数(){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>

我希望这些语句按顺序运行——也就是说,输出是

<预><代码>0123456

相反,输出是

<预><代码>0123645

即使删除内部 Promise 也会给出在我看来是矛盾的结果.12之前输出,65之前输出.

有人可以向我解释一下吗?

我注意到的一点是,每次重新分配 p 都会给我们我期望的顺序.

解决方案

你早看到 6 的原因是因为你没有链接,你分支了.

当您调用 p.then().then().then() 时,您将获得一系列承诺,必须以正确的顺序执行.
但是,如果您调用 p.then().then();p.then(),你有 2 个 promise 附加到 p - 本质上是创建一个分支,第二个分支将与第一个分支一起执行.

您可以通过确保将它们链接在一起来解决此问题p = p.then().then();p.then();

仅供参考,您几乎从不想分支,除非您将它们重新组合在一起(例如 Promise.all),或者有意创建一个即发即弃"的分支.

I'm still learning JavaScript Promises, 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

Instead, the output is

0
1
2
3
6
4
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?

Something I have noticed is that reassigning p each time gives us the order I would expect.

解决方案

The reason you see 6 early is because you didn't chain, you branched.

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.

You can fix this by ensuring you chain them together p = p.then().then(); p.then();

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 Promise then() 排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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