"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > When do JavaScript Promise .then() Handlers Execute in Relation to Each Other?

When do JavaScript Promise .then() Handlers Execute in Relation to Each Other?

Published on 2024-12-11
Browse:843

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

  1. Promises Resolve Asynchronously:
    Promises are resolved independently of the current thread of execution. This means the .then() handlers are called asynchronously after the current thread finishes.
  2. Promises Execute in a Queue:
    .then() handlers are scheduled to run after the preceding handler completes. They are essentially queued, which is why you see 1, 2 "A", and 3 "B" printed in that order.
  3. Inner Promises Create Independent Chains:
    Promises created within nested .then() handlers, like the Promise.resolve('C') and Promise.resolve('D'), create new, independent promise chains. These inner chains do not inherently synchronize with the outer chain.
  4. Order of Execution is Not Deterministic:
    The order of execution for these independent chains is not guaranteed. In this case, the promise engine chooses to execute the .then() handlers on lines 5 and 12 before the ones on lines 6 and 7.

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.

Release Statement This article is reprinted at: 1729739979 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3