Home > Web Front-end > JS Tutorial > body text

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

Susan Sarandon
Release: 2024-10-25 08:19:28
Original
394 people have browsed it

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);
Copy after login

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
Copy after login

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);
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!