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 未定義、4 未定義、9 "D"、 10 未定義、5 未定義、および 6.
免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。
Copyright© 2022 湘ICP备2022001581号-3