Async /await for asynchronous programming

The guide language

In the previous section we learned about the event-loop mechanism. In this section we will learn about async/await for asynchronous programming. Everyone has heard that async/await is the ultimate solution for asynchronous programming. So let’s experience the charm of async/await!

async

First, let’s take a look at some code:

    console.log(async function(){})
Copy the code

What happens if you prefix a method with the async keyword and print it out? The answer is:

[AsyncFunction (anonymous)] returns the result indicating that this is an asynchronous method. If you feel nothing special, let’s look at the following code:

    console.log(async function () {});
    console.log(function () {
      return new Promise((resolve, reject) = > {
        resolve(6);
      });
    });
Copy the code

The result is:



From the result, we can see that only methods with async will return AsyncFunction, and methods without async keyword only return a Function.

Let’s change this code again:

    console.log((async function () {}) ());console.log(
      (function () {
        return new Promise((resolve, reject) = > {
          resolve(6);
        });
      })()
    );
Copy the code

Here we make both methods immediately executable, and we get the following result:

Here, we get two Promise objects, but they come from different backgrounds. The first method returns a Promise because of the async keyword. The second one returns a Promise object because we returned a Promise object inside the function.

Here we can draw a conclusion:The async keyword declares a method as an asynchronous method and wraps the value returned by the method as a Promise object. Async is just a syntactic sugar wrapper for promise!

await

2. Await can be used to evaluate an expression. 3. With await, errors thrown within an asynchronous operation can be tried… Catch catch

Next, we can verify these features of await one by one with examples.

Await blocks the process

    async function test() {
      await new Promise((resolve, reject) = > {
        setTimeout(() = > {
          console.log("1");
          resolve("1");
        }, 1000);
      });
      console.log("2");
    }

    test();
Copy the code

The code output is:

When we remove the await:

    async function test() {
      new Promise((resolve, reject) = > {
        setTimeout(() = > {
          console.log("1");
          resolve("1");
        }, 1000);
      });
      console.log("2");
    }
    
    test();
Copy the code

The result is:

From the comparison of these two pieces of code, we can conclude that await blocks the process.

Await can evaluate expressions

demo1:

    async function test() {
      let a = await new Promise((resolve, reject) = > {
        setTimeout(() = > {
          resolve("1");
        }, 1000);
      });
      console.log(a);
    }

    test();
Copy the code

Results:

demo2:

    async function test() {
      let a = await (2 * 3 + 5);
      console.log(a);
    }

    test();

Copy the code

Results:

demo3:

    async function test() {
      let a = await new Promise((resolve, reject) = > {
        setTimeout(() = > {
          reject(new Error("test"));
        }, 1000);
      });
      console.log(a);
    }

    test();
Copy the code

Results:

With await, errors thrown within an asynchronous operation can be tried… Catch catch

Try… without await Catch whether an error thrown in an asynchronous task can be caught.

    function test() {
      try {
        new Promise((resolve, reject) = > {
          setTimeout(() = > {
            reject(new Error("test"));
          }, 1000);
        });
      } catch (error) {
        console.log(error);
      }
    }

    test();
Copy the code

The result of running in a browser: a global error is thrown!

Case with await keyword:

    async function test() {
      try {
        await new Promise((resolve, reject) = > {
          setTimeout(() = > {
            reject(new Error("test"));
          }, 1000);
        });
      } catch (error) {
        console.log(error);
      }
    }

    test();
Copy the code

Result: Error caught by catch method!

conclusion

So much for understanding async and await. So, see you next time. Good good study, day day up!