Async is a new feature in ES7 and is essentially the syntactic sugar of Generator. Since it is grammatical sugar, let’s first talk about its improvement.

1. Improvement of Async Generator

1.1. Improvement of writing method

The Generator functions;function* foo() {
  yield "b";
}
Async functions;async function foo() {  await "b"; } Copy the code

By comparison, we find that the async function is written with the Generator function’s asterisk replaced with the async keyword, and the yield keyword with the await keyword.

1.2. Built-in actuator

Generator functions must rely on an actuator for execution, whereas async functions come with an actuator. So async functions don’t need to be executed by the next method like Generator functions. They can be executed just like normal functions.

1.3 better practicability

The co module convention is that yield can only be followed by a Thunk function or a Promise object, whereas async’s await command can be followed by Promise objects and values of primitive types (numeric, string, and Boolean, etc.). This will automatically change to an immediately resolved Promise.

1.4. Return Promise

The async function returns a Promise object and can try the THEN method, unlike the Generator function, which returns an Iterator.

2, the basic usage of async

The async function returns a Promise object, and you can add callbacks using the THEN method. When a function executes, it returns the await as soon as it encounters the await, waits until the async operation completes, and then executes the following statement in the function body. The await must be in the async function, otherwise an error will be reported.

async function foo() {
  let result = await "b";
  return result;
}
foo().then((value) = > console.log(value)); // b
Copy the code

As you can see, the value returned by the return statement in the async function becomes an argument to the then callback. When an error is thrown in the async function, it is passed as an argument to the catch function.

async function foo() {
  throw new Error("Error");
}
foo().catch((err) = > console.log(err)); / / Error: Error
Copy the code

3, await expression

In general, await objects are mostly await objects. When a Promise object is returned, the result of the Promise object in the resolved state is returned, or in the case of a rudimentary data type, the result is returned directly.

async function foo() {
  let result = await new Promise((resolve) = > resolve(1));
  return result;
}
foo().then((value) = > console.log(value)); / / 1
Copy the code

When an await is followed by a thenable object, it is treated as if it were a Promise object.

let thenable = {
  name: "Jack".  then: (resolve) = > resolve("2"),
};
async function foo() {
 let result = await thenable;  return result; } foo().then((value) = > console.log(value)); / / 2 Copy the code

When an error occurs in a Promise object following await:

async function foo() {
  await Promise.reject("Something went wrong.");
  await Promise.resolve("1");
}
foo()
 .then((value) = > console.log(value))  .catch((err) = > console.log(err)); / / make a mistake Copy the code

When there are multiple await statements, as long as a Promise after one of the await promises reports an error, all statements following the expression are not executed. If you want to execute later statements, you can use try… catch…

async function foo() {
  try {
    await Promise.reject("Something went wrong.");
  } catch (err) {
    console.log(err); / / make a mistake
 }  return await Promise.resolve("1"); } foo()  .then((value) = > console.log(value)) / / 1  .catch((err) = > console.log(err)); Copy the code

There is another way:

async function foo() {
  await Promise.reject("Something went wrong.").catch((err) = > console.log(err)); / / make a mistake
  return await Promise.resolve("1");
}
foo()
 .then((value) = > console.log(value)) / / 1  .catch((err) = > console.log(err)); Copy the code

Because the catch catches the error before it. Note that if there are more than one await, the await is not emitted at the same time. Instead, the next await is emitted after the previous Promise succeeds. The promise. all method is used if the Promise is emitted simultaneously.

async function foo() {
  let [a, b] = await Promise.all([new Promise(resolve= >resolve(1)), new Promise(resolve= >resolve(2)));  return [a, b];
}
Copy the code

After the language

Related articles:

  • Take you relearn ES6 | var, let and the difference between const
  • Take you relearn ES6 | Promsie
  • Take you relearn ES6 | Generator
  • Take you relearn ES6 | Async and Await
  • Take you relearn ES6 | Set and Map
  • Take you relearn ES6 | Symbol (more than just a new data type)
  • Take you relearn ES6 | Exprort (keep in mind that the output is variable)
  • Take you relearn ES6 | proxy and defineProperty

I think it’s ok, please give me a thumbs up when I leave, and we can study and discuss together!

You can also follow my blog and hope to give me a Start on Github, you will find a problem, almost all my user names are related to tomatoes, because I really like tomatoes ❤️!!

The guy who wants to follow the car without getting lost also hopes to follow the public account or scan the qr code below 👇👇👇.

I am a primary school student in the field of programming, your encouragement is the motivation for me to keep moving forward, 😄 hope to refueling together.

This article was typeset using MDNICE