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

MySQL SQL statement analysis and query optimization detailed explanation

How to obtain SQL statements with performance iss...

Understanding Nginx Current Limitation in One Article (Simple Implementation)

Nginx is now one of the most popular load balance...

How to deploy zabbix_agent in docker

zabbix_agent deployment: Recommendation: zabbix_a...

vue.js Router nested routes

Preface: Sometimes in a route, the main part is t...

What command is better for fuzzy searching files in Linux?

1. Introduction This article mainly explains how ...

React implements the expansion and collapse function of complex search forms

Give time time and let the past go. In the previo...

9 Practical Tips for Creating Web Content Pages

Content 1. Give readers a reason to stay. Make the...

Detailed summary of mysql sql statements to create tables

mysql create table sql statement Common SQL state...

Introduction to the use of alt and title attributes of HTML img tags

When browser vendors bend the standards and take i...