Home >Web Front-end >JS Tutorial >When do JavaScript Promise .then() Handlers Execute in Relation to Each Other?
Understanding the Execution Order in JavaScript Promises
Promises in JavaScript offer an asynchronous programming model where code is executed once a specific event, or promise, is fulfilled. However, when dealing with multiple promises, it's essential to understand the order of execution to avoid unpredictable behavior.
Consider the following code snippet:
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);
Upon execution, you may observe the following order of output:
1 2 "A" 3 "B" 7 "C" 4 "B" 8 undefined 9 "D" 5 undefined 10 undefined 6
Understanding the Execution Order
Recommendations
To ensure a specific order of execution, avoid creating unsynchronized promise chains and instead rely on linking promises in a sequential manner. Return promises from inner .then() handlers to chain them with the parent promise, as shown below:
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);
With this approach, the execution order becomes entirely deterministic: 1, 2 "A", 3 "B", 7 "C", 8 undefined, 4 undefined, 9 "D", 10 undefined, 5 undefined, and 6.
The above is the detailed content of When do JavaScript Promise .then() Handlers Execute in Relation to Each Other?. For more information, please follow other related articles on the PHP Chinese website!