Home  >  Article  >  Web Front-end  >  Why Doesn\'t the Order of Promise Execution Match Expectations in JavaScript?

Why Doesn\'t the Order of Promise Execution Match Expectations in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 08:01:28398browse

Why Doesn't the Order of Promise Execution Match Expectations in JavaScript?

What is the order of execution in JavaScript promises?

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:

  1. All .then() handlers are invoked asynchronously after the current thread of execution finishes This consistency includes promises resolved synchronously, such as Promise.resolve().then(...), to prevent timing bugs.
  2. There's no specified order for setTimeout() versus scheduled .then() handlers. While the implementation used places a pending .then() handler before a pending setTimeout(), the Promises/A specification allows for scheduling either before or after setTimeout().
  3. Independent Promise chains don't have predictable execution order.
  4. If execution order is crucial, avoid creating races dependent on minute implementation details. Instead, link promise chains to force a specific order.
  5. Avoid creating independent promise chains within .then() handlers unless it's a 'fire and forget' scenario.

Line-by-Line Analysis:

  1. The initial promise chain is initiated, and a .then() handler is attached. As Promise.resolve() resolves instantly, the first .then() handler is scheduled to run after the current JavaScript thread finishes. Subsequent .then() handlers at the top level chain after the first and will only execute after the first one completes.
  2. The setTimeout() is run at the end of the thread of execution, and a timer scheduled.
  3. After synchronous execution finishes, the event queue runs the remaining tasks.
  4. The .then() handler defined in Line 1 executes, and '2 "A"' is logged.
  5. The subsequent .then() handler is invoked, and a new independent promise chain is created with a .then() handler scheduled to run when the current thread of execution finishes. This handler prints '3 "B"' before the child chain's .then() handler runs, which prints '7 "C"'.
  6. The .then() handler defined in Line 12 is then invoked, and again a new promise chain is created, scheduling a .then() handler. '4 "B"' is logged from this handler.
  7. The scheduled .then() handler from the child chain is run, printing '8 undefined'.
  8. The .then() handler defined in Line 19 is subsequently invoked, and another independent promise chain is created, scheduling a .then() handler. '5 undefined' is printed from this handler.
  9. Finally, the .then() handler defined in Line 15 is invoked, and '10 undefined' is printed.
  10. The setTimeout() executes last.

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!

Statement:
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