理解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
瞭解執行順序
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.
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3