Problem:
The following snippet demonstrates the use of JavaScript promises, and the order of execution is intriguing.
<code class="javascript">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);</code>
The result indicates the order of execution is:
1 2 "A" 3 "B" 7 "C" 4 "B" 8 undefined 9 "D" 5 undefined 10 undefined 6
The question raised is why the execution order is not 1, 2, 3, 4..., and how does the expectation of 1, 2, 3, 4... differ from the result?
Answer:
Comments:
Running promises within a .then() handler without returning them from the .then() callback creates a new, unattached promise sequence that doesn't synchronize with the parent promises in any way. This is generally considered a bug and some promise engines issue warnings when it occurs, as it's usually not the intended behavior. A valid use case might be a 'fire and forget' operation where neither errors nor synchronization is a concern.
Promise.resolve() promises within .then() handlers create new Promise chains that run independently of the parent chain. With actual asynchronous operations, such as AJAX calls, there's no predictable behavior for independent, disconnected promise chains. The timing of completion is indeterminate, like launching four AJAX calls in parallel where the order of completion is unknown. In the code provided, all operations are synchronous, resulting in consistent behavior, but this shouldn't be relied upon as the design purpose of promises is asynchronous execution.
Summary:
Line-by-Line Analysis:
Conclusion:
The lack of a specific order in Promise.resolve() promise executions within .then() handlers, as well as the indeterminacy of .then() handler scheduling versus setTimeout() for various engines, highlight the importance of controlling execution order through chaining promises.
The above is the detailed content of Why Doesn't the Order of Promise Execution Match Expectations in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!