This article will introduce you to asynchronous programming in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Asynchronous means non-synchronous....
This section may be a bit boring, but it is a very important concept in JavaScript and is very useful. It is necessary to learn.
Purpose
Improve development efficiency and write easy-to-maintain code
Why is the data updated but the DOM not updated? ?
// 异步批量更新DOM(vue-nextTick)
// <p id="app">{{num}}</p>
new Vue({
el: "#app",
data: {
num: 0,
},
mounted() {
let dom = document.getElementById("app");
while (this.num !== 100) {
this.num++;
}
console.log("Vue num=" + this.num, "DOM num=" + dom.innerHTML);
// Vue num=100,DOM num=0
// nextTick or setTimeout
},
});
Copy after login
The reasons for asynchronous generation
Cause: single thread (one point in time, only do one thing), the browser's JS engine is single threaded caused.
Single thread means that there is only one thread responsible for interpreting and executing IavaScript code in the JS engine. You might as well call it the main thread.
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. The previous task is completed before the next task is executed.
First take a look at the thread diagram of the browser kernel:
Among them, The rendering thread and the JS thread are mutually exclusive .
Suppose there are two functions, one modifying and one deleting, operating a DOM node at the same time. If there are multiple threads, if the two threads are executed at the same time, there will definitely be a deadlock and there will be problems.
Why JS should be designed as single-threaded, because of the special environment of the browser.
Advantages and disadvantages of single thread:
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, the subsequent Tasks must be queued and waited, 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.
Common blockage (infinite loop):
while (true) {}
Copy after login
JS was originally designed to be a script language that runs in the browser, so we didn’t want to make it so complicated, so we just designed It has become a single thread, that is, can only do one thing at a time.
In order to solve single-thread blockingthis shortcoming: asynchronous is generated.
Asynchronous : Buy instant noodles => Boil water (the water boils and the kettle sounds - callback) => Watch TV => Cook noodles (the noodles are ready and the kettle rings - callback) => Watch TV => Call me when it's done => Eat instant noodles
Watching TV is an asynchronous operation, and the sound of the kettle is a callback function.
Asynchronous Programming
Most of the code in JS is executed synchronously. Only a few functions are executed asynchronously. Asynchronously executed code requires asynchronous programming. .
Characteristics of asynchronous code: It is not executed immediately, but needs to wait and be executed at a certain point in the future.
Synchronous code
Asynchronous code
##<script>Code
Network request (Ajax)
I/O operation
Timer (setTimeout, setInterval)
Rendering operation
Promise(then)
async/await
Callback function
The most common way to write asynchronous code is to use a callback function.
HTTP network request (the request is successful and the xx operation is performed after identification) DOM event binding mechanism (the xx operation is performed after the user triggers the event) Timer (setTimeout, setInterval) (Execute xx operation after reaching the set time)
The shortcomings of the callback function are also obvious, and it is easy to produce callback hell:
Three ways of asynchronous programming
callback
function getOneNews() {
$.ajax({
url: topicsUrl,
success: function(res) {
let id = res.data[0].id;
$.ajax({
url: topicOneUrl + id,
success: function(ress) {
console.log(ress);
render(ress.data);
},
});
},
});
}
Copy after login
promise
function getOneNews() {
axios
.get(topicsUrl)
.then(function(response) {
let id = response.data.data[0].id;
return axios.get(topicOneUrl + id);
})
.then((res) => {
render(res.data.data);
})
.catch(function(error) {
console.log(error);
});
}
Copy after login
async/await
async function getOneNews() {
let listData = await axios.get(topicsUrl);
let id = listData.data.data[0].id;
let data = await axios.get(topicOneUrl + id);
render(data.data.data);
}
If multiple asynchronous codes exist at the same time, what should be the order of execution? Which one is executed first and which one is executed later?
Macro tasks and micro tasks
Division of asynchronous code, asynchronous code is divided into macro tasks and micro tasks.
The above is the detailed content of Take you step by step to understand asynchronous programming in JavaScript. For more information, please follow other related articles on the PHP Chinese website!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
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
1. Why use asynchronous programming? Traditional programming uses blocking I/O, which means that the program waits for an operation to complete before continuing. This may work well for a single task, but may cause the program to slow down when processing a large number of tasks. Asynchronous programming breaks the limitations of traditional blocking I/O and uses non-blocking I/O, which means that the program can distribute tasks to different threads or event loops for execution without waiting for the task to complete. This allows the program to handle multiple tasks simultaneously, improving the program's performance and efficiency. 2. The basis of Python asynchronous programming The basis of Python asynchronous programming is coroutines and event loops. Coroutines are functions that allow a function to switch between suspending and resuming. The event loop is responsible for scheduling
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.
Asynchronous programming, English Asynchronous Programming, means that certain tasks in the program can be executed concurrently without waiting for other tasks to complete, thereby improving the overall operating efficiency of the program. In Python, the asyncio module is the main tool for implementing asynchronous programming. It provides coroutines, event loops, and other components required for asynchronous programming. Coroutine: Coroutine is a special function that can be suspended and then resumed execution, just like a thread, but a coroutine is more lightweight and consumes less memory than a thread. The coroutine is declared with the async keyword and execution is suspended at the await keyword. Event loop: Event loop (EventLoop) is the key to asynchronous programming