The use of async/await and matters needing attention

Source: Internet
Author: User

With Async/await, with promise, you can process asynchronous processes by writing code that resembles synchronization, improving the simplicity and readability of your code. This article introduces the basic usage of async/await and some matters needing attention. await

Introduction to MDN:

The await operator is used to wait for a Promise object that can only be used within the asynchronous function async functions.

The syntax for await is very simple:

[Return_value] = await expression;

Where expression is a Promise object or any value to wait for;

The results of the implementation of await expression are as follows:

If expression is a Promise object and it is fulfilledwith a value of x, the return value is x.

If expression is a Promise object, and it is rejectedwith an exception e, throws an exception e.

If expression is not a Promise object, the expression is processed into a fulfilled object that is Promise with the expression value, and then returns the final value of the Promise object (that is, Expression value). This usage doesn't make much sense, so when you actually use it, you try to await followed by a Promise object.

It is also noted that await waits for the Promise object to cause the async function to suspend execution until the Promise object resolution Async function continues to execute.

Take a piece of code to see:

Async function foo () {
    var a = await new Promise (resolve) => {
        settimeout (() => {
            resolve (1);
        }, 20 );
    Console.log (a); Output in 2nd seconds: 1

    try {
        var b = await new Promise (Resolve, Reject) => {
            settimeout (() => {
                reject (2); 
  }, 1000);
        }
    catch (e) {
        console.log (e);//3rd SEC output: 2
    }

    //function paused for 2 seconds before continuing with
    var sleep = await new Promise ((resolve) =&G T {
        settimeout (() => {
            resolve (' sleep ');
        };}
    )

    ; var C = await 3;
    Console.log (c); Output at 5th seconds: 3
}

foo ();
Async

Use the Async function to define an asynchronous function with the following syntax:

Async function Name ([param[, param[, .... param]]] {statements}

The return value of the Async function is special: The actual return value of the Async function is always a Promise object, regardless of what value is returned in the function body. The details are:

If a value x is returned in the Async function, the actual return value of the Async function is always promise.resolve (x), regardless of the type of x value.

So what kind of Promise does Promise.resolve (x) eventually return? Take a look at MDN's introduction:

The Promise.resolve (value) method returns a Promise object that is parsed with the given value. But if the value is a thenable (i.e. with a then method), the returned promise "follows" the Thenable object, using its final state (referring to the resolved/rejected/pending/settled) Otherwise, the Promise object is returned with this value as a successful state.

Next look at the application of a piece of code. Let's say there's a scenario where you need to get data 1through request 1 , and then get Data 2by asking 2 and carrying the data 1 . And then show it to the page.

Programme I:

Async function ShowData () {
    //pretends to request data 1
    var data1 = await new Promise ((resolve) => {settimeout (
        () => {
  resolve (' data1 ');
        }, 1000);
    };

    pretends to request data 2 and this request relies on data 1
    var data2 = await new Promise ((resolve) => {settimeout (
        () => {resolve (
            ' data2 '); c10/>}, 1000);

    Display Data 2
    console.log (DATA2);
}

ShowData ();

The above code is sequentially fetched to data 1 and 2, and then the data is shown 2.

Since the Async function always returns a promise, you can also return a async function to get the Data 2 promise, call the function, and then use the then method to get the data, the code is as follows:

async function GetData () {//Fake request data 1 var data1 = await new Promise ((resolve) => {
        SetTimeout (() => {resolve (' data1 ');
    }, 1000);

    });
        pretends to request data 2 and this request relies on data 1 return new Promise ((resolve) => {settimeout () => {resolve (' data2 ');
    }, 1000);
}); } getData (). Then ((v) => {console.log (v);}); 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.