


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:
- 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.
- 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().
- Independent Promise chains don't have predictable execution order.
- If execution order is crucial, avoid creating races dependent on minute implementation details. Instead, link promise chains to force a specific order.
- Avoid creating independent promise chains within .then() handlers unless it's a 'fire and forget' scenario.
Line-by-Line Analysis:
- 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.
- The setTimeout() is run at the end of the thread of execution, and a timer scheduled.
- After synchronous execution finishes, the event queue runs the remaining tasks.
- The .then() handler defined in Line 1 executes, and '2 "A"' is logged.
- 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"'.
- 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.
- The scheduled .then() handler from the child chain is run, printing '8 undefined'.
- 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.
- Finally, the .then() handler defined in Line 15 is invoked, and '10 undefined' is printed.
- 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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.

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.

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

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 in JavaScript? When processing data, we often encounter the need to have the same ID...

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