Table of Contents
What is the order of execution in JavaScript promises?
Home Web Front-end JS Tutorial Why Doesn\'t the Order of Promise Execution Match Expectations in JavaScript?

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

Oct 25, 2024 am 08:01 AM

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

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles