Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the microtask Microtask in the JavaScript event loop

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

How to understand the micro-task Microtask in the JavaScript event cycle, I believe that many inexperienced people are at a loss about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Micro task (Microtask)

Promise handlers (handlers). Then,. Catch, and. Finally are all asynchronous.

Even if an promise is immediately executed by the code under resolve,.then, .catch, and .finally, it is executed before these handlers (handler).

The sample code is as follows:

Let promise = Promise.resolve (); promise.then (() = > alert ("promise done!")); alert ("code finished"); / / this alert is displayed first

If you run it, you will see code finished first, then promise done.

This is strange, because the promise must have been completed from the beginning.

Why was the .then triggered later? What's going on here?

Micro task queue (Microtask queue)

Asynchronous tasks require proper management. To this end, the ECMA standard specifies an internal queue PromiseJobs, often referred to as the "micro task queue (microtask queue)" (V8 term).

As stated in specification [1]:

Queues (queue) are first-in, first-out: the tasks that enter the queue first run first.

Tasks in the task queue begin to be executed only when there are no other tasks running in the JavaScript engine.

Or, simply put, when an promise is ready, its .then / catch/finally handlers (handler) are queued: but they are not executed immediately. When the JavaScript engine finishes executing the current code, it fetches the task from the queue and executes it.

This is why "code finished" is displayed first in the above example.

Promise's handler (handler) always passes through this internal queue.

If there is a chain that contains multiple .then / catch/finally, then each of them is executed asynchronously. That is, it is queued first and then executed when the current code execution is complete and the previously queued handlers (handler) are complete.

What if the order of execution is important to us? How do we get code finished to run after promise done?

It's simple, just use .then to queue it as follows:

Promise.resolve (). Then () = > alert ("promise done!"). Then () = > alert ("code finished"))

Now the code is executing as expected.

Unprocessed rejection

Remember the unhandledrejection event in the chapter [2] on using promise for error handling?

Now we can see exactly how JavaScript discovers unprocessed rejection.

If the error of a promise is not processed at the end of the micro-task queue, an "unprocessed rejection" appears.

Normally, if we expect an error to occur, we add .catch to the promise chain to handle the error:

Let promise = Promise.reject (new Error ("Promise Failed!")); promise.catch (err = > alert ('caught')); / / will not run: error has been processed window.addEventListener (' unhandledrejection', event = > alert (event.reason))

But if we forget to add .catch, the JavaScript engine triggers the following event after the micro-task queue is cleared:

Let promise = Promise.reject (new Error ("Promise Failed!")); / / Promise Failed! Window.addEventListener ('unhandledrejection', event = > alert (event.reason))

What if we deal with this error later? For example:

Let promise = Promise.reject (new Error ("Promise Failed!")); setTimeout (() = > promise.catch (err = > alert ('caught')), 1000); / / Error: Promise Failed! Window.addEventListener ('unhandledrejection', event = > alert (event.reason))

Now, if we run the above code, we will see Promise failed first, then caught.

If we don't know anything about microtask queues, we might think, "Why is the unhandledrejection processor (handler) running? we have captured (catch) and processed error!"

But now we know that a unhandledrejection is generated when all the tasks in the micro-task queue are completed: the engine checks the promise, and if any of the promise has a "rejected" state, the unhandledrejection event is triggered.

In the above example, the .catch that was added to the setTimeout is also triggered. It is triggered only after the unhandledrejection event occurs, so it doesn't change anything (doesn't work).

Promise processing is always asynchronous because all promise activities go through the internal "promise jobs" queue, also known as the "micro-task queue" (V8 term).

Therefore, the. then/catch/finally handler handler is always called after the current code is complete

If we need to ensure that a piece of code is executed after .then / catch/finally, we can add it to the chained invocation. Then.

In most JavaScript engines (including browsers and Node.js), the concept of microtask is closely related to "event loop" and "macrotasks". Since these concepts are not directly related to promise, we will introduce them in the article illustrating the JavaScript event loop: microtasks and macrotasks.

After reading the above, have you mastered how to understand the micro-task Microtask in the JavaScript event loop? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report