What is javascript asynchronous? What is the use?
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.
What is js asynchronous?
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,
Asynchronous-Timer
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
Asynchronous-ajax
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,
Task queue and event loop
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.
Why do we need to continuously scan the contents of the task queue after the main thread's task is executed?
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.
What are the scenarios for front-end asynchronous?
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 is asynchronous required:
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.Asynchronous and Parallel
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!

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

AI Hentai Generator
Generate AI Hentai for free.

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

Summary: Asynchronous programming in C++ allows multitasking without waiting for time-consuming operations. Use function pointers to create pointers to functions. The callback function is called when the asynchronous operation completes. Libraries such as boost::asio provide asynchronous programming support. The practical case demonstrates how to use function pointers and boost::asio to implement asynchronous network requests.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

3 common problems and solutions in asynchronous programming in Java frameworks: Callback Hell: Use Promise or CompletableFuture to manage callbacks in a more intuitive style. Resource contention: Use synchronization primitives (such as locks) to protect shared resources, and consider using thread-safe collections (such as ConcurrentHashMap). Unhandled exceptions: Explicitly handle exceptions in tasks and use an exception handling framework (such as CompletableFuture.exceptionally()) to handle exceptions.

The Go framework uses Go's concurrency and asynchronous features to provide a mechanism for efficiently handling concurrent and asynchronous tasks: 1. Concurrency is achieved through Goroutine, allowing multiple tasks to be executed at the same time; 2. Asynchronous programming is implemented through channels, which can be executed without blocking the main thread. Task; 3. Suitable for practical scenarios, such as concurrent processing of HTTP requests, asynchronous acquisition of database data, etc.

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

The advantages of asynchronous programming in PHP include higher throughput, lower latency, better resource utilization, and scalability. Disadvantages include complexity, difficulty in debugging, and limited library support. In the actual case, ReactPHP is used to handle WebSocket connections, demonstrating the practical application of asynchronous programming.

Advantages: Performance improvement: parallel task execution, making full use of multi-core processors. Scalability: Easily scale to handle larger workloads. Responsiveness: The main thread does not block, keeping the application responsive. Resource Optimization: Avoid the need for locking and synchronization structures. Challenge: Code Complexity: Managing multiple independent tasks. Difficulty debugging: Tasks are executed in different threads or coroutines. Error handling: Error handling in a concurrent environment is complex and requires additional measures. Practical case: downloading files in parallel, using Goroutine to download multiple files at the same time, showing how asynchronous programming can improve performance.

Yes, PHP functions support asynchronous programming. Since PHP 7.2, coroutines have been introduced, lightweight user-level threads that allow asynchronous execution. The steps to use the coroutine include: defining the coroutine function, using yield to pause the coroutine, and using Generator::resume() to resume execution. Web application performance can be improved by executing operations such as HTTP requests asynchronously.
