首頁 > 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學習者快速成長!