This article brings you what is javascript asynchronous? What is the use? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
We know that JavaScript is single-threaded, which is related to its purpose. As a browser scripting language, JavaScript's main purpose is to interact with users and manipulate the DOM. This determines that it can only be single-threaded, otherwise it will cause very complex synchronization problems. For example, suppose JavaScript has two threads at the same time. One thread adds content to a certain DOM node, and the other thread deletes the node. In this case, which thread should the browser use?
The so-called "single thread" means that only one task can be completed at a time. If there are multiple tasks, they must be queued. After the previous task is completed, the next task will be executed, and so on.
The advantage of this mode is that it is relatively simple to implement and the execution environment is relatively simple; the disadvantage is that as long as one task takes a long time, subsequent tasks must be queued up, which will delay the execution of the entire program. Common browser unresponsiveness (suspended death) is often caused by a certain piece of Javascript code running for a long time (such as an infinite loop), causing the entire page to get stuck in this place and other tasks cannot be performed.
Ajax's synchronous request will cause the browser to freeze, because it will lock the browser's UI (buttons, menus, scroll bars, etc.) and block all user interactions. Ajax in jquery has such a synchronous request Function must be used with caution, especially when the amount of data requested is large, avoid using synchronous requests.
Give a few chestnuts to feel asynchronous
The background interface uses easy-mock, the official address: https://easy-mock.com/
ajax uses axios, the basic code is as follows
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>javascript异步</title> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <button>点击</button> <script> { let myData = null //ajax请求 function ajax() { axios.get('https://easy-mock.com/mock/5b0525349ae34e7a89352191/example/mock') .then(data => { console.log("ajax返回成功");// handle success myData = data.data console.log(myData); }) .catch(error => { // console.log(error); // handle error console.log("ajax返回失败"); }) } } </script> </body> </html>
Let’s see the effect by adding some js,
console.log(myData); setTimeout(() => { console.log('定时器'); }, 2000); console.log(myData);
Output, there should be no suspense
//null //null //定时器
Execution order:
Execute the first one first console.log(myData);
Then the timer is encountered and the timer is suspended (that is, the timer is suspended)
Continue to execute the second console.log(myData);
Nothing can be executed js code, go back and continue executing the suspended task
Continue to look at the next chestnut
console.log(myData); ajax() console.log(myData);
Look at the output, there is still no suspense
//null //null //ajax返回成功 //{success: true, data: {…}}(这是接口返回的数据,我们不必关心返回的具体内容,只要知道返回了就好,陌上寒注)
The execution sequence is basically similar to the timer above, so I won’t go into details here.
Combine the two chestnuts, let’s take a look at the
console.log(myData); ajax() setTimeout(() => { console.log('定时器'); }, 2000); console.log(myData);
output.
//null //null //ajax返回成功 //{success: true, data: {…}} //定时器
Did you find the problem? When two asynchronous functions meet, which one will be executed first? Whoever runs faster will be executed first?
It can also be said that, in fact, this leads to another knowledge point,
Both console.log(myData); are executed synchronously, they are both Executed on the main thread of js,
There is also a task queue outside the main thread, and the task queue stores content that needs to be executed asynchronously
When the main thread finishes running, the tasks in the task queue will be executed. (Continuously repeat scanning) until the task queue is cleared
Observe this code
console.log(1); setTimeout(function () { console.log(2); }, 1000); console.log(3);
Output: 1, 3, 2, there is nothing to explain
Look at another piece of code
setTimeout(function(){console.log(1);}, 0); console.log(2);
Output: 2, 1, why is this?
console.log(2); In the main thread, it is executed first,
setTimeout(function(){console.log(1);}, 0); is placed in the task queue,
only The content in the task queue will not be executed until the main thread has finished executing.
Looking at this code will help you understand
console.log(myData); ajax() setTimeout(() => { console.log('定时器'); }, 2000); console.log(myData); const btn = document.querySelector('button') btn.onclick = () => { console.log("点击了"); }
We added a click event to the button button, and kept clicking the button while the browser was refreshing (of course Manually click)
Look at the output:
//null //null //(10次输出)点击了 //ajax返回成功 //{success: true, data: {…}} //定时器 //点击了
Can we understand why the main thread has to scan the task queue in a loop?
Each round of the event loop is called a tick (do you think of nextTick in vue?)
When user interaction occurs (mouse click event, page scroll event, window size change event, etc.), ajax, Timers, timers, etc. will add events to the task queue in the event loop and then wait for execution.
Scheduled tasks: setTimeout, setInverval
Network requests: ajax requests, dynamic loading of img images
Event binding or DOM event, such as a click event, I don't know when it clicked, but before it clicked, what should I do. When registering a type of event with addEventListener, the browser will have a separate module to receive this thing. When the event is triggered, a certain module of the browser will throw the corresponding function into the asynchronous queue. If now If the execution stack is empty, this function will be executed directly.
Promise in ES6
When a wait may occur Situation
When the program cannot be blocked like alert during the waiting process
Therefore, all "waiting situations" need to be asynchronous
In one sentence, you need to use asynchronous
when you need to wait but cannot block the program.Don’t confuse asynchronous and parallel,
Asynchronous is single-threaded, parallel is multi-threaded
Asynchronous: The tasks of the main thread are synchronized Only after the execution is completed will the asynchronous tasks in the task queue be executed sequentially
Parallel: Two or more event chains are executed alternately over time, so that from a higher level, they appear to be running at the same time (although Only handle one event at any time)
The above is the detailed content of What is javascript asynchronous? What is the use?. For more information, please follow other related articles on the PHP Chinese website!