Asynchronous programming

JS works in single-threaded mode

The JS runtime environment supports two modes of API, namely synchronous mode and asynchronous mode. Synchronization mode apis such as console.log. Asynchronous modes such as setTimeout.

Eventloop

The event loop in the JS runtime environment is essentially an infinite loop function. It is used to listen for unprocessed tasks in the JS call stack, and if not, the message is pulled from the message queue (i.e. the callback function) and pushed into the JS call stack for executionCopy the code

The message queue

Messages in message queues are essentially callback functions. So message queues can also be called callback queues.Copy the code

Macro task

All messages (that is, callback functions) stored in message queues in the JS runtime environment belong to macro tasks.Copy the code

Micro tasks

A microtask is an API that executes immediately after the current macro task completes. These apis including Promise. Then/process. NextTick/MutationObserver.Copy the code

Promise

An ES6 syntax specification that represents a real-world promise. There are three states: hang, cash and fail. Used to solve the callback hell problem caused by callback nesting. Promises are essentially ES6 classes. There are four kinds of instance methods, namely the resolve, reject, then, the catch. There are two static methods: All and race. The promise.then method supports chained calls.Copy the code

Generator

While the chained calls to Promise.then successfully solved the callback hell problem, readability was still a bit out of line with code reading habits, which is where generators come in. You can define generator functions with function *. Generator functions are special in that when they are called, the body of the generator function is not executed immediately. It simply returns the generator object that contains the next function, which is called, and the generator function starts executing and pauses at yield. Multiple yields can be placed in the body of a generator function. An external call to the next function of a generator object passes its arguments to the variable (optionally) to the left of the paused yield in the generator function body and continues execution until the next yield is reached.Copy the code

Await/Async

Syntactic candy in ES7 for writing asynchronous code more intuitively. And make sure that the order in which the code is executed is the order in which the code is written. Defined by async function. Call asynchronous code in the function body with the await keyword.Copy the code