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

js to realize the function of uploading pictures

The principle of uploading pictures on the front ...

MySQL uses find_in_set() function to implement where in() order sorting

This article introduces a tutorial about how to u...

Summary of Vue component basics

Component Basics 1 Component Reuse Components are...

How to use display:olck/none to create a menu bar

The effect of completing a menu bar through displ...

Seven different color schemes for website design experience

The color matching in website construction is ver...

MySQL msi installation tutorial under windows10 with pictures and text

1. Download 1. Click the latest download from the...

CSS3 to achieve floating cloud animation

Operation effect html <head> <meta chars...

Example of implementing TikTok text shaking effect with CSS

In daily development, front-end students often ar...

MySQL study notes on handling duplicate data

MySQL handles duplicate data Some MySQL tables ma...

MySQL stored procedure in, out and inout parameter examples and summary

Stored Procedures 1. Create a stored procedure an...

jQuery to achieve sliding stairs effect

This article shares the specific code of jQuery t...

Detailed explanation of the use of MySQL sql_mode

Table of contents Preface sql_mode explained The ...

MySQL uses limit to implement paging example method

1. Basic implementation of limit In general, the ...

Detailed explanation of cocoscreater prefab

Table of contents Prefab How to create a prefab T...