The use and methods of async and await in JavaScript

The use and methods of async and await in JavaScript

async function and await keyword in JS

function hellworld() {

    return "Hello! Beautiful world!";

}

console.log(hellworld()); // Hello! Beautiful world!

async function asyHellworld() {

    return "Hello! Beautiful world!";

}

console.log(asyHellworld()); // Promise { 'Hello! Beautiful world! ' }

The normal function hellworld will simply return the string hello! Beautiful world! , and the async function will return a Promise object.

If you need to use the value returned by the asynchronous function, you need to add a .then() block after it, as follows:

async function asyHellworld() {

    return "Hello! Beautiful world!";

}

asyHellworld().then((str) => console.log(str)); // Hello! Beautiful world!

The await keyword will ensure that the asynchronous function's Promise will complete and return a result before continuing to execute other code that may need to wait for the value.

async function asyHellworld() {

    return await Promise.resolve("Hello! Beautiful world!");

}

asyHellworld().then(console.log); // Hello! Beautiful world!

This code, while simple, does show the usage of the await keyword and how it should work with Promise objects within a function body.

Next, to make the code easier to understand, remove the Promise syntax in the code, as follows:

async function asyHellworld() {

    return "Hello! Beautiful world!";

}

async function printHello() {

    const strHello = await asyHellworld();

    console.log(strHello);

}

printHello();

The above code can more intuitively see the use of async and await. Usually async and await are used to handle asynchronous operations, which is a way to turn asynchrony into synchronization.

async declares a function to represent this asynchronous function, and await is used to wait for an asynchronous operation in the function to complete.

Through the above introduction, we have a preliminary understanding of async and await, so what can they be used for?

The await keyword will ensure that the asynchronous function's Promise will complete and return a result before continuing to execute other code that may need to wait for the value.

Therefore, when processing AJAX asynchronous requests, such as in VUE projects, the usual processing method is as follows:

login(username, password).then((loginResult) => {

    // Processing request after login request is sent console.log("Login successful!");

});

And using await can be handled like this:

const loginResult = await login(username, password);

console.log(loginResult);

One thing to note here is that await can only be used in asynchronous functions. The above code is problematic. If it is processed in the store, it needs to be changed to:

const actions = {

    async [LOGIN]({ commit }, payload) {

        const { username, password } = payload;

        const loginResult = await login(username, password);

        console.log(loginResult);

    },

};

It can be seen here that the advantage is reflected when dealing with a then chain consisting of multiple Promises.

Another common use is to pause the program, that is, the sleep method. The implementation code is as follows:

const sleep = (ms) => {
    return new Promise((resolve) => setTimeout(resolve, ms));
};

(async () => {
    console.log("Start execution, print hello for 10 seconds");
    await sleep(10 * 1000);
    console.log("Hello");
})();

This is the end of this article about the use and methods of async and await in JavaScript. For more relevant Js async and await content, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone 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
  • Detailed explanation of JavaScript Promise and Async/Await
  • How to use async and await in JS

<<:  MySQL time difference functions (TIMESTAMPDIFF, DATEDIFF), date conversion calculation functions (date_add, day, date_format, str_to_date)

>>:  Detailed explanation of script debugging mechanism in bash

Recommend

Practice of deploying web applications written in Python with Docker

Table of contents 1. Install Docker 2. Write code...

Recommend a cool flashing alarm button

The effect is as follows: The code is as follows ...

Detailed explanation of the use of React list bar and shopping cart components

This article example shares the specific code of ...

Use Firebug tool to debug the page on iPad

How to debug a page on iPad? When using iOS 5, you...

Linux C log output code template sample code

Preface This article mainly introduces the releva...

Vue installation and use

Table of contents 1. Vue installation Method 1: C...

Create a movable stack widget function using flutter

This post focuses on a super secret Flutter proje...

Linux Domain Name Service DNS Configuration Method

What is DNS The full name of DNS is Domain Name S...

The difference between delete, truncate, and drop and how to choose

Preface Last week, a colleague asked me: "Br...

How to create dynamic QML objects in JavaScript

1. Dynamically create objects There are two ways ...

JavaScript Canvas implements Tic-Tac-Toe game

This article shares the specific code of JavaScri...

Modify the style of HTML body in JS

Table of contents 1. Original Definition 2. JS op...

How to use mysqldump to backup MySQL data

1. Introduction to mysqldump mysqldump is a logic...