Async/await keywords

ES6 has added “async” and “await” keywords. The first time I saw this keyword was in a small program project shared by others. I have not seen “async” and “await” before, so I did a Search on Baidu

async

Async is used to declare an asynchronous function, and async itself means “asynchronous.” Its advantage is that it handles the chain of then calls

Async returns a Promise object. If async returns a value inside the function, promise.resolve () is called to help you wrap the Promise object. If async throws an error inside the function, We call promise.reject () internally to return the Promise object. We need to use.then() to handle the Promise object when we can’t use the await keyword on the outside of the function. For example:

async function test1() {

    return 1

}



console.log(test1())    // Promise {<fulfilled>: 1}



test1().then(res= > {

    consoloe.log(res)   / / 1

})
Copy the code
async function test2() {

    const p1 = Promise.resolve(1)

    p1.then(res= > {

        console.log(1)})const result = await p1

    console.log(result)     / / 1

}
Copy the code

Now, what happens if async doesn’t return a value? The answer is given below

await

As the name implies, await is waiting for a return value, which can be followed by a function or a direct value. The await wraps the ordinary value into a Promise object and then waits for the Promise object to be resolved, no further execution, until the Promise object is resolved and the return result is returned, for example

async function test3() {

    const result = await 3  // equivalent to await promise.resolve (3)

    console.log(result)     / / 3

}
Copy the code

If the async function does not return any value, this is undefined

async function test5() {

    console.log("test5")}async function test() {

  const result = await test5()

  console.log(result)   // undefined

}
Copy the code

Note: The await keyword can only be placed inside async functions

The following explains the use of async and await by simulating asynchronous requests

function returnAfter2seconds(number) {

    return new Promise(resolve= > {

        setTimeout(() = > {

            resolve(number)

        }, 2000); })}// This function is used to simulate an asynchronous request and returns number after 2 seconds

async function testResult() {

    let first = await returnAfter2seconds(30);

    let second = await returnAfter2seconds(50);

    let third = await returnAfter2seconds(30);

    console.log(first + second + third);    // After 6s, enter 110 on the console

}
Copy the code

Here we see the role of async and await, which lets us get out of callback hell when we actually write code

For example: if the following code does not use async and await

function getZhihuColumn(id) {

    const url = `https://zhuanlan.zhihu.com/api/columns/${id}`

    axios.get(url).then(res= > res.json())

                  .then(column= > {

                    console.log(`Name: ${column.name}`)

                    console.log(`Intro: ${column.intro}`)

    })

}

getZhiHuColumn('feweekly')
Copy the code

With the async and await keywords, the following code becomes pretty neat and looks like synchronized code

async function getZhihuColumn(id) {

    const url = `https://zhuanlan.zhihu.com/api/columns/${id}`

    const res = await axios.get(url)

    const column = await res.json()

    console.log(`Name: ${column.name}`)

    console.log(`Intro: ${column.intro}`)

}

getZhiHuColumn('feweekly')
Copy the code

Promise is designed to solve asynchronous callbacks, and async/await is designed to optimize it so that asynchronous code looks like it’s synchronized. Maybe this is the ultimate solution to callback hell

“Async and await” are used, and what do they do? What is the return value of async “.

You will find out after reading this article

In fact, this is an accidental discovery in someone else’s source code, but we will learn a lot of knowledge by digging into the keyword we have never seen before. Although async and await are not used much in actual code, they will certainly help us a lot once they are used

Recommended reading

  1. Let you understand async/await once, solve callback hell
  2. Understand JavaScript async/await