」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > JavaScript Promise .then() 處理程序何時會相互關聯執行?

JavaScript Promise .then() 處理程序何時會相互關聯執行?

發佈於2024-12-11
瀏覽:175

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。從內部 .t​​hen() 處理程序返回 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