”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > JavaScript Promise .then() 处理程序何时相互关联执行?

JavaScript Promise .then() 处理程序何时相互关联执行?

发布于2024-12-11
浏览:122

When do JavaScript Promise .then() Handlers Execute in Relation to Each Other?

理解 JavaScript Promises 中的执行顺序

JavaScript 中的 Promises 提供了一种异步编程模型,其中代码在特定事件或 Promise 发生后执行,已满足。但是,在处理多个 Promise 时,必须了解执行顺序以避免不可预测的行为。

考虑以下代码片段:

Promise.resolve('A')
  .then(function(a){console.log(2, a); return 'B';})
  .then(function(a){
     Promise.resolve('C')
       .then(function(a){console.log(7, a);})
       .then(function(a){console.log(8, a);});
     console.log(3, a);
     return a;})
  .then(function(a){
     Promise.resolve('D')
       .then(function(a){console.log(9, a);})
       .then(function(a){console.log(10, a);});
     console.log(4, a);})
  .then(function(a){
     console.log(5, a);});
console.log(1);
setTimeout(function(){console.log(6)},0);

执行后,您可能会观察到以下输出顺序:

1
2 "A"
3 "B"
7 "C"
4 "B"
8 undefined
9 "D"
5 undefined
10 undefined
6

理解执行顺序

  1. Promises 异步解析:
    Promises 的解析独立于当前执行线程。这意味着 .then() 处理程序在当前线程完成后被异步调用。
  2. Promises 在队列中执行:
    .then() 处理程序被安排在前面的处理程序之后运行处理程序完成。它们本质上是排队的,这就是为什么您会看到按顺序打印 1、2 个“A”和 3 个“B”。
  3. 内部承诺创建独立链:
    创建的承诺在嵌套的 .then() 处理程序中,例如 Promise.resolve('C') 和 Promise.resolve('D'),创建新的、独立的 Promise 链。这些内链本质上并不与外链同步。
  4. 执行顺序不确定:
    这些独立链的执行顺序无法保证。在这种情况下,promise 引擎选择在第 6 行和第 7 行之前执行第 5 行和第 12 行的 .then() 处理程序。

Recommendations

为了确保特定的执行顺序,请避免创建不同步的 Promise 链,而是依赖于按顺序链接 Promise。从内部 .then() 处理程序返回 Promise,将它们与父 Promise 链接起来,如下所示:

Promise.resolve('A').then(function (a) {
    console.log(2, a);
    return 'B';
}).then(function (a) {
    var p = Promise.resolve('C').then(function (a) {
        console.log(7, a);
    }).then(function (a) {
        console.log(8, a);
    });
    console.log(3, a);
    return p; // Link the inner promise to the parent chain
}).then(function (a) {
    var p = Promise.resolve('D').then(function (a) {
        console.log(9, a);
    }).then(function (a) {
        console.log(10, a);
    });
    console.log(4, a);
    return p; // Link the inner promise to the parent chain
}).then(function (a) {
    console.log(5, a);
});

console.log(1);

setTimeout(function () {
    console.log(6)
}, 0);

通过这种方法,执行顺序变得完全确定:1, 2 "A", 3 "B", 7 "C", 8 undefined, 4 undefined, 9 "D", 10 个未定义、5 个未定义和 6.

版本声明 本文转载于:1729739979如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3