How to use async and await in JS

How to use async and await in JS

1. async

async creates an asynchronous function to define a code block in which asynchronous code is run;

How to turn it into an asynchronous function? It starts with the keyword async , which can be placed before a function.

async function f() {
  return 1;
}
 
f().then(alert); // 1
 
//The results are the same as above async function f() {
  return Promise.resolve(1);
}
 
f().then(alert); // 1
 
//You can also use arrow function let hello = async () => { return "1" };
hello().then((value) => console.log(value))
//The return value can also be simplified like this hello().then(console.log)

One of the characteristics of asynchronous functions: the return value of the function is guaranteed to be promise .

Adding the async keyword to function declarations tells them to return promise instead of a value directly. Additionally, it avoids any potential overhead of synchronous functions to support the use of await .

2. await:

await only works inside asynchronous functions. It can be placed in any asynchronous, await keyword to make the JavaScript engine wait until promise is completed and the result is returned. While waiting for promise , other code that is waiting to be executed has a chance to execute.

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

async function f() {
  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("boom!"), 1000)
  });
 
  let result = await promise; // Wait until promise resolves. alert(result); // "Boom!"
}
 
f(); //Get result and continue to execute. So the above code displays "Boom!" after 1 second.

Note: await actually pauses the execution of the function until the promise status becomes fulfilled, and then continues execution with the result of the promise. This behavior does not consume any CPU resources, because the JavaScript engine can handle other tasks at the same time: executing other scripts, processing events, etc.

3. Comprehensive Application

With async/await you can get rid of the .then() code 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()
.catch(e => {
  console.log('Problem: ' + e.message);
});

You wrap your code with fewer .then() blocks, and it looks a lot like synchronous code, so it's very intuitive. It’s very cool to use this way!

This is the end of this article about how to use JS async/await . For more information about JS async/await usage, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to use async and await correctly in JS loops
  • How to use async await elegantly in JS
  • A more elegant error handling method in JavaScript async await
  • A simple and in-depth study of async and await in JavaScript
  • The use and methods of async and await in JavaScript
  • Detailed explanation of JavaScript Promise and Async/Await

<<:  Docker case analysis: Building a MySQL database service

>>: 

Recommend

Specific usage instructions for mysql-joins

Table of contents Join syntax: 1. InnerJOIN: (Inn...

Vue implements Modal component based on Teleport

Table of contents 1. Get to know Teleport 2. Basi...

Tutorial on installing MYSQL8.0 on Alibaba Cloud ESC

Open the connection tool. I use MobaXterm_Persona...

A brief discussion on three methods of asynchronous replication in MySQL 8.0

In this experiment, we configure MySQL standard a...

Docker installs the official Redis image and enables password authentication

Reference: Docker official redis documentation 1....

Using vue3 to imitate the side message prompt effect of Apple system

Table of contents Animation Preview Other UI Libr...

Tutorial on installing jdk1.8 on ubuntu14.04

1. Download jdk download address我下載的是jdk-8u221-li...

Solution for converting to inline styles in CSS (css-inline)

Talk about the scene Send Email Embedding HTML in...

JS implements the rock-paper-scissors game

This article example shares the specific code of ...

Docker uses root to enter the container

First run the docker container Run the command as...