理解 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