JavaScript is a single-threaded programming language that requires an asynchronous approach to achieve high performance. However, asynchronous programming is often confusing when you are just starting to learn.
What is synchronous/asynchronous
For example: if now you need to do two things, boil water and eat. So how do you allocate your time?
Method 1: Boil water first, then wait for the water to boil before eating.
Method 2: Connect the power to the kettle, and go directly to eat without waiting for the water to boil. After the water is boiled, the buzzer of the kettle will sound, which can remind you to do the next step.
One of the above methods belongs to synchronous programming. If the previous program has not been executed, the subsequent program must wait for the previous execution to complete before continuing to execute. If a program is a very time-consuming operation (such as reading a file on a hard disk, initiating a network request, etc.), the program will block, which is manifested in a sharp drop in performance in a single-threaded programming language.
The second method belongs to asynchronous programming. When encountering a time-consuming IO operation, the runtime will not wait for this operation, but will directly return the result and continue to execute downward, and the program will not block. But how to get the result of IO operation? When the IO operation is performed, a callback function is passed in. After the IO operation is completed, the callback function will be called and the data will be passed in. The callback function will perform subsequent operations on the data (such as storing to the database, transmitting data through the network, etc.).
Callback function (Callback)
Simply put, it is to pass a function as a parameter to another function.
/**
* parameter calculator
* @param {Number} a parameter a
* @param {Number} b parameter b
* @param {Function} callback callback function
* @returns detailed description
*/
function deal(a, b, callback){
const result = callback(a, b)…
The post Understanding JS asynchronous programming, detailed explanation of callback, Promise, Generator, async/await usage first appeared on Lenix Blog .
This article is reprinted from https://blog.p2hp.com/archives/9834
This site is for inclusion only, and the copyright belongs to the original author.