ES8 async/await solves the problem of organizing code with asynchronous structures. There are only two keywords async and await

What is async function

In short, async functions are syntactic sugar for generator functions; The generator is the result of adding a built-in executor and returns a Promise object that can be used to retrieve the result and proceed with the next operation

Basic usage

The async function returns a Promise object, and you can add callbacks using the then method. When a function executes, upon encountering an await, it returns, waits for the asynchronous operation to complete, and then executes the statement following the function body

Use the async keyword to make functions asynchronous, but overall the code is still evaluated synchronously

grammar

Return a Promise object

The async function returns a Promise object. If a return statement returns a value (undefined if there is no return), the Promise. Resolve () is wrapped as a term object that becomes an argument to the then callback

An error is thrown inside the async function, which causes the state of the returned Promise object to become Reject. The thrown error object is received by the catch method callback

The state change of the Promise object

The state of the Promise object returned by async can change in two ways:

  1. All Promise objects following the internal await command have finished executing
  2. A return statement or a throw error is encountered
  3. The then callback function is executed only after the asynchronous operation inside the async function completes

Await orders

Because asynchronous functions are primarily for tasks that do not complete immediately, the ability to pause and resume execution is naturally required. Use the await keyword to suspend the execution of asynchronous function code and the wait period is resolved

Normally, an await command is followed by a Promise object and returns the result of that object or, if it is not a Promise object, the corresponding value

If the Promise object after the await command becomes REJECT, the reject argument is received by the catch callback

The state of any Promise object following an await statement changes to reject, and the entire async suspends execution

Error handling

If an asynchronous operation following await fails, the Promise returned by the async function is rejected

The way to prevent errors is to put await into a try… In the catch block

Implement multiple repeated attempts

Using a try… A catch structure with async/await implements a function that has been tried many times. If an await operation succeeds, the loop will be pushed. If an await operation fails, the loop will be caught and the next loop will be performed

const superagent = require("superagent");
const NUM_RETRIES = 3;

async function test() {
  let i;
  for (i = 0; i < NUM_RETRIES; ++i) {
    try {
      await superagent("/bar.txt");
      break;
    } catch (error) {}
  }
  console.log(i);
}

test();
Copy the code

Use caution points

  1. ‘await’ may result in ‘reject’, so try… In the catch block
  2. If multiple await statements do not have a secondary relationship, it is best to fire them simultaneously using promise.all
  3. The await command can only be used in async functions
  4. Async functions can preserve the run stack

The implementation principle of async function

This is to wrap the Generator function and the auto-executor in one function