Home >Web Front-end >JS Tutorial >Why is the JavaScript Promise execution order not linear as expected?
Problem
Consider the following JavaScript code that uses promises:
<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 output is as follows:
<code class="text">1 2 "A" 3 "B" 7 "C" 4 "B" 8 undefined 9 "D" 5 undefined 10 undefined 6</code>
The question is about the execution order, specifically the numbers 1, 2, 3, 7, and so on. Why is it not the expected linear order 1, 2, 3, 4, ...?
JavaScript promises follow specific execution rules:
In the given code:
Since the independent promise chains created within .then() handlers do not have a predictable execution order, the ordering of 3, 7, 4, 8, 9, 5, 10 depends on the specific promise engine implementation.
To ensure a specific execution order for asynchronous operations, it is recommended to:
In the given example, returning the Promise.resolve('C') promise from the .then() handler on line 4 would link the promise chains and result in the expected sequential execution order.
The above is the detailed content of Why is the JavaScript Promise execution order not linear as expected?. For more information, please follow other related articles on the PHP Chinese website!