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

Summary of Common Terms in CSS (Cascading Style Sheet)

If you use CSS don't forget to write DOCTYPE, ...

How to create an index on a join table in MySQL

This article introduces how to create an index on...

Steps to install RocketMQ instance on Linux

1. Install JDK 1.1 Check whether the current virt...

Native JS to achieve blinds special effects

This article shares a blinds special effect imple...

First experience of creating text with javascript Three.js

Table of contents Effect Start creating text Firs...

How to manage large file uploads and breakpoint resume based on js

Table of contents Preface Front-end structure Bac...

How to view the status of remote server files in Linux

As shown below: The test command determines wheth...

Detailed steps for deploying Microsoft Sql Server with Docker

Table of contents 1 Background 2 Create a contain...

JavaScript implements password box input verification

Sometimes it is necessary to perform simple verif...

How to let https website send referrer https and http jump referrer

This article describes a proposal for a metadata ...

Discussion on the problem of iframe node initialization

Today I suddenly thought of reviewing the producti...

Real-time refresh of long connection on Vue+WebSocket page

Recently, the Vue project needs to refresh the da...

HTML set as homepage and add to favorites_Powernode Java Academy

How to implement the "Set as homepage" ...

Example of customizing the style of the form file selection box

Copy code The code is as follows: <!DOCTYPE ht...