In short async/await is a syntectic candy based on Promises that makes asynchronous code easier to write and read.

A, async:

Async creates an asynchronous function to define a block of code in which to run asynchronous code;

How do you make an asynchronous function? Start with the async keyword, which can be placed before a function

async function f() {
  return 1;
}
 
f().then(alert); / / 1
 
// The result is the same up and down
 
async function f() {
  return Promise.resolve(1);
}
 
f().then(alert); / / 1
 
// Arrow functions can also be used
let hello = async() = > {return "1" };
hello().then((value) = > console.log(value))
// The return value can also be simplified like this
hello().then(console.log)
Copy the code

One of the characteristics of asynchronous functions is that the function is guaranteed to return a promise.

Adding the async keyword to a function declaration tells them to return a promise instead of returning a value directly. Furthermore, it avoids any potential overhead of synchronization functions to support the use of await.

Second, await:

Await only works in asynchronous functions. It can be placed in any asynchronous, keyword await so that the JavaScript engine waits until the promise completes and returns the result. While waiting for the promise, the rest of the code waiting to execute gets a chance to execute.

You can use await when calling any function that returns a Promise, including Web API functions.

async function f() {
  let promise = new Promise((resolve, reject) = > {
    setTimeout(() = > resolve("Dong!"), 1000)});let result = await promise; // Wait until the promise resolve executes
 
  alert(result); / / "dong!"
}
 
f();// Get the result and proceed. So the code above says "boom!" after 1 second. .
Copy the code

Note: Await actually suspends the execution of the function until the promise state is complete, and then continues with the promise result. This behavior does not cost any CPU resources because the JavaScript engine can handle other tasks simultaneously: executing other scripts, handling events, and so on.

Three, comprehensive application:

With async/await there are.then() blocks everywhere because await will wait.

async function A() { let response = await fetch('c.jpg'); let myBlob = await response.blob(); let objectURL = URL.createObjectURL(myBlob); let image = document.createElement('img'); image.src = objectURL; document.body.appendChild(image); } (A). The catch (e = > {the console. The log (' : '+ e.m essage); });Copy the code

Encapsulate the code with fewer.then() blocks, and it looks a lot like synchronous code, so it’s very intuitive. It’s great to use!

  • Male _ no. ❤; Front-end honest person, you can exchange and learn with small partners!