Someone on Twitter posted a video "Understanding async/await in 7 seconds", the address is here

The split achievement is a change of writing: callback function -> promise -> async/await

js inherently supports asynchronous. If your data depends on asynchronous requests, you need to get it in its callback. Once you write too much, it will form callback hell, as shown in the following figure

回调函数模式

Later, ES6 came out with promise. Promise means promise. The scenario is as follows:

Fiancee: You must come back!

Soldiers going out to fight: I promise

In this way, there is a sequence in the writing method, no need to nest, but concatenate (but it looks very clear after a line break)

promise模式

The problem with promise is that its context is still asynchronous, when getDate do something after getting the data (then)

People's habitual thinking is synchronous, that is, when they write, they write, they are happy when they are happy, and they are angry when they are angry. They didn't say to wait five seconds before laughing.

So promise is good, but it can be written in another way - async/await

async/await模式

async/awiat are bound together and are indispensable

const a = await getData() where a is the result of requesting data, which is more in line with human thinking in understanding


山头人汉波
394 声望555 粉丝