Detailed explanation of async and await

1. Concept

Async is the abbreviation of asynchronous, which stands for asynchronous request, because the grammar stipulates that await can only appear in async, await can be simply understood as the abbreviation of async wait, that is to say, async is used to declare that a function is asynchronous, and await is to wait for this The asynchronous method is executed

2. async function

The async function will return a promise object. If a direct value is returned directly in the function, async will encapsulate the direct value into a promise object through promise.resolve, see the code

 async function test() {
        return "test"
    }
    let res = test()
    console.log(res);

The result is this

 So he can be used with the then method

  async function test() {
        return "test"
    }
   test().then(res=>{
    console.log(res);
   })

result

3. The role of await

await is an operator used to form an expression. The result of the operation depends on the result of the operation he is waiting for. If he is waiting for a promise object, he will get the value of resolve in the promise as the result of his operation.

 

 Use async and await instead as below

 4. Advantages of async and await

It can be seen from the above examples that the results of async, await and then for asynchronous calls are not significantly different, and there are even some more codes between async and await, which seems a bit wrong.

The advantage of async and await is that it handles multiple promise chain calls, and a single promise cannot reflect its advantages. Just imagine, if one has multiple steps, and the call of each step depends on the result of the previous step, we know that we can Use the then method to continuously make chain calls to solve the problem of callback hell, then async and await optimize this chain call.

 

Does it feel clearer?

Guess you like

Origin blog.csdn.net/qq_45662523/article/details/126683975