In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to understand JavaScript async". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to understand JavaScript asynchronism.
Guide reading
First of all, to understand that JavaScript is a single-threaded language, to understand why it is designed to be single-threaded, let's first talk about the initial application scenario of JavaScript.
Secondly, how to deal with multithreaded tasks in a single-threaded language.
Third, synchronous and asynchronous processes and how to understand async.
Then, what kind of problems arise when solving complex logical business.
And then, how to solve this problem.
= > Promise/.then (), async/await
Finally, talk about micro task and macro task.
The initial Application scenario of JavaScript
Originally, JavaScript was designed as a browser scripting language to achieve user interaction, but in order to avoid multithreading to bring us a lot of unnecessary trouble, such as: one thread is deleting a node, and another thread is modifying this node, which thread should be the main thread?
Therefore, the designer designed it as a single-threaded language.
It is specified in H5 that JS can have multiple child threads, but the child threads are still dependent on the main thread and cannot operate on the node.
Why use multithreading?
Disadvantages of single threading:
A "fatal" disadvantage of single threading is that it can cause blocking.
Because it is a single thread, the task is processed according to the first-in-first-out principle when the program is running, and it is precisely for this reason that after the main thread encounters a time-consuming operation, the subsequent task enters the waiting state. If the CPU is occupied at this time, it doesn't matter, but if the time-consuming task is an operation that does not take up the CPU, take a chestnut: request data from the server. At this time, the CPU goes in and out of the idle state, but the program is not finished, which forms a block.
Inspiration:
When performing a time-consuming operation and affecting the normal operation of the code, we can ignore the operation and suspend it. Deal with the rest of the task first, and then execute the task when the main thread is empty. As a result, synchronous and asynchronous tasks appear.
Synchronous and asynchronous and program running flow
With regard to this piece of content, the author suggests that, as a whole, it may be easier to understand by combining the contents of this piece.
We can think of synchronous tasks as tasks executed in the main thread and asynchronous tasks as executing in child threads.
The execution process of synchronous and asynchronous tasks:
The synchronization task runs normally, and there is no special case that it will be executed all the time.
When the main thread runs to an asynchronous task, a child thread is arranged to run the asynchronous task, and when the asynchronous task is finished, an event is sent to the task queue. Indicates that the asynchronous task can enter the main thread for execution.
When not considering the micro and macro tasks described below, when our program runs, we first execute the synchronous task, then send it to the child thread to run after the asynchronous task is executed, and an event is sent to the task queue at the end of the run. After the execution of the synchronization task, that is, after the main thread is empty, the main thread will ask the task queue whether an event has been received. If not, the main thread will always ask. This process is called event loop;. If so, the event will be executed. Until the program is complete.
Event
We mentioned the concept of event above, which can be thought of as a callback function returned by an asynchronous task, that is, the event runs on the main thread. An asynchronous task must have a callback function.
Extension: asynchronous functions must return a Promise object
With regard to the incident, the elder Ruan Yifeng wrote:
In addition to IO device events, the events in the Task queue also include user-generated events (such as mouse clicks, page scrolls, and so on). As long as the callback function is specified, these events will enter the "task queue" when they occur, waiting for the main thread to read.
"callback hell."
In the actual development, in order to achieve some logical requirements, multi-layer callback function nesting may be used. At this time, the readability of the code is very poor. People call it "callback hell."
Promise object
Represents the final completion or failure of the asynchronous operation
Objective: to disassemble the multi-layer nesting form of callback function into the form of chain call.
Essence: the object returned by the function, which binds the callback function to avoid passing the callback function as an argument to the upper-level function from the beginning.
A Promise is bound to be in these states:
Pending: the initial state, which is neither honoured nor rejected
Cashed (fulfilled): means that the operation has successfully completed the resolve
Rejected (rejected): indicates that the operation failed reject
The use of Promise: generally used as the return value of a function
Const fn = function () {
Return new Promise ((resolve,reject) = > {
If (ture) {
Resolve (a)
} else {
Reject (b)
}
})
}
Fn ()
.then ((res) = > {function with return value})
.then ((res) = > {function with return value})
.then ((res) = > {function with return value})
...
.then (res= > {Last function})
/ / if the request in the Promise object is completed, then the value of resolve is passed to the callback function in then as an argument to execute the then method
Catch () can be appended to the end of the chained structure to catch errors (values returned by reject), and subsequent then will not execute
/ / you can add a .finally () at the end to perform the cleanup operation and this method will be executed regardless of whether the request is successful or not.
Async/await
Is the syntax sugar of Promise; makes tedious then () and lengthy chained calls a little longer to read
Specific usage:
/ / Asynchronous function 1
Function getData (data) {
Return new Promise ((reslove) = > {
Reslove (data)
})
}
/ / Asynchronous function 2
Function sayHello (data) {
Return new Promise ((reslove) = > {
Reslove (data)
})
}
/ / Asynchronous function
Async function fn () {
/ / await is equivalent to. Then () getData () is equivalent to a callback function
/ / await must be used in the body of the function modified by async
Const promiseA = await getData ('info')
Const promiseB = await sayHello (promiseA)
Console.log (promiseB)
}
Talking about Micro tasks and Macro tasks
Micro task
Note: the code in the Promise object is synchronous, and the callback function in the then () method is asynchronous.
In then () are micro tasks
Macro task
Timer is a macro task
Code execution order formula: first synchronous then asynchronous, first micro task then macro task
In short, the same micro macro
At this point, I believe you have a deeper understanding of "how to understand JavaScript async". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.