JS asynchronous programming

I. Lead-up content

Before we get into the specifics of asynchronous programming, we need to know what synchronous programming is and what asynchronous programming is, and the two work very differently.

1.1 What is Synchronization? What is asynchronous?

Let me give you an example: if you need to do two things, one is to cook and the other is to listen to a song, then the execution process of cooking and listening to the song is synchronous programming process. The execution of cooking first and listening to music while cooking is an asynchronous programming process.

1.2 Why is Javascript single threaded

JS is responsible for the interaction between the browser and the user, because JS needs to operate on the DOM, so it must be single-threaded. If you are JS, please imagine if there are multiple threads operating on the same DOM at the same time, you will be mad. Because of this, so the queue waiting time is too long, so we have now called JS asynchronous programming scheme.

The core and method of asynchronous programming

2.1 How to Implement Asynchronous Programming? What is at the heart of asynchronous programming?

There are many ways to implement asynchronous programming, such as callbacks, promise objects, event listeners, publish/subscribe, etc., but the core of all asynchronous programming is callback. Here’s an example of what a callback is:

If you want to put your headphones on the headset rack after cooking, then you tell your partner that you need to put your headphones on the headset rack after you finish listening to the song, and then you listen to the song. In this process, putting the headset back into the headset holder is the callback function, which is the operation that you need to perform after the task is completed. You are the caller of the asynchronous operation, and your object is the performer of the asynchronous operation. In summary, the function defined by the caller and given to the performer to execute is the callback function.

2.2 How to solve the callback hell problem?

Speaking of callback hell, surely many partners are not strange, this problem also troubled me when I was a beginner of JS, I think at the beginning but was tortured by this problem for a period of time. Then let me tell you about the callback hell, specifically the callback hell is, when you perform DOM events, such as in the click on the links on a page, enter the operation, the browser will send a number of HTTP requests to the server, quietly carry can identify the parameters of the background, wait for the server to return data, this process is an asynchronous callback, When many functions depend on each other, the code can be nested layer upon layer, making it look huge and disgusting.

It is precisely because the callback hell is not conducive to reading, but also not conducive to maintenance, so the predecessors to solve this problem, in many aspects of the efforts, this time I want to share with you a core point of JS asynchronous programming – promise, please carefully analyze what I said:

(1) What is promise?

Promise is a constructor that returns a Promise object. A promise is an object that may produce a single value at some point in the future. Here’s a good way to describe the promise mechanism:

For example, if you go to a hamburger restaurant to buy a hamburger package, you have paid for it, but you are told that the hamburger is sold out, and the clerk solves your problem by giving you a hamburger coupon, which will not expire, and she asks you to come back tomorrow to get the coupon for the hamburger. You can exchange your coupon for a hamburger, but you can’t be sure if you’ll get a hamburger tomorrow, but you can be sure that you’ll get a hamburger at some point in the future.

(2) Three states of promise itself (the state will not change after it changes)

(1) fulfilled: success

(2) rejected: failure

(3) pending: wait

(3) The use of promise

Promise gives you some prototype methods for handling the state

1.promise.prototype.then :

The Promise object completes the pending -> depressing state through the internal resolve function. The promise then retains this state. You can handle states through then. Example: pm.then((val) =>{console.log(val); })

With the Rejected state, the then method accepts two functions


new Promise(function(resolve,reject){

	setTimeout(() = >{
	
​    	reject(new Error('err'))},2000).then(null.(error) = >{

​    		console.log(error); })})Copy the code

2.promise.prototype.catch:

In such chain calls, we only need to use then to process the depressing state, and add catch at the end of the chain to process errors in a unified manner.

new Promise((resolve,reject) = >{

  setTimeout(() = >{

​    resolve = 100;

  },2000).then(result= >{

​    return result * num;

​    return result / 2; }).catch(err= >{

​      console.log(err); })})Copy the code

3.promise.prototype.finally():

I put this API at the end, and at this point you’re probably wondering why? Because it does not care what the previous promise changes to, it will execute the callback inside.

new Promise((resolve,reject) = >{

  setTimeout(() = >{

​    resolve = 100;

  },2000).then(result= >{

​    return result * num;

​    return result / 2; }).catch(err= >{

​      console.log(err);

​      console.log('complete')})})Copy the code

4.promise.all

Promise.all([A,B]).then(resA,resB) =>{

  //do something

}
Copy the code

5. Promise chain call

The then method of the Promise object returns a privileged Promise object

The subsequent THEN methods register callbacks for the promise returned by the previous THEN

The return value of the callback function from the previous THEN method is used as an argument to the callback from the later THEN method

If the callback returns a Promise, the subsequent then method’s callback waits for it to end

2.3 Sequence of EventlLoop Execution

An EventLoop, called event polling or EventLoop, listens for the call stack and message queue. Once the stack is empty, an EventLoop takes the first callback function from the message queue and pushes it onto the stack to execute it.

Just my personal point of view, I am so understand it: the code executed from top to bottom, if there are any micro tasks on the micro task queue, acer tasks into the task queue, after all the code is executed stack, on a mission to micro task list, after all the small tasks to be solved, then to macro task queue to solve all the macros.

Note:

1. When the current macro task is executed, the system returns to the list of microtasks to see if there are any microtasks to be executed. If there are any microtasks, the system executes the microtasks first.

2. Microtasks do not need to queue at the end of the queue.

This is the end of today’s sharing, here is a small salted fish from the art industry, welcome everyone to put forward valuable suggestions, and discuss the technical knowledge of the front-end, I hope everyone can become a front-end veteran in the near future.