首页 > web前端 > js教程 > 正文

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

Susan Sarandon
发布: 2024-10-25 08:19:28
原创
394 人浏览过

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

了解 JavaScript Promise 中的执行顺序

JavaScript 中的 Promise 提供了一种异步编程模型,其中代码在特定事件或 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() 处理程序。

建议

为了确保特定的执行顺序,请避免创建不同步的 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 个未定义、4 个未定义、9 个“D”、10 个未定义、5 个未定义和 6。

以上是JavaScript Promise .then() 处理程序何时相互关联执行?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!