Quickly understand and use ES7 Await/async

Source: Internet
Author: User
Tags generator

Await/async is one of the most important features of ES7, it is the best asynchronous solution for JS so far. Although not entered in the ES2016, but soon arrived, is now in Es-next Stage 4 phase.

https://segmentfault.com/a/1190000007116715

Direct examples, such as we need to get in order: Product data => user Data => comment data old friend Ajax

The traditional writing, no need to explain

Get Product Data
Ajax (' Products.json ', (products) => {
    console.log (' ajax/products >>> ', Json.parse ( Products));

    Get User Data
    Ajax (' Users.json ', (users) => {
        console.log (' ajax/users >>> ', Json.parse (users));

        Get Comment Data
        Ajax (' Products.json ', (comments) => {
            console.log (' ajax/comments >>> ', Json.parse ( Comments));});
not a new friend, Promise.

Promise has been mentioned for a long time and is also a part of ES6. Promise can eliminate callback hell bring the Pyramid of doom, compared to the code clearer, but still can't write synchronization code intuitive degree.

Promise
//encapsulates Ajax, returns a Promise
function requestp (URL) {return
    new Promise (function (resolve, reject) { C3/>ajax (URL, (response) => {
            Resolve (Json.parse (response));}
        )

;} Get Product data
REQUESTP (' Products.json '). Then (products) => {
    console.log (' Promises/products >>> ', Products);
    Gets the user data return
    requestp (' Users.json ');
}). Then (users) => {
    console.log (' Promises/users >>> ', users);
    Get Comment Data return
    requestp (' Comments.json ');
}). Then ((comments) => {
    console.log (' promises/comments >>> ', comments);
});
a strong new friend generators

Generators is also ES6 a new feature that can suspend/execute code. Yield represents a pause, Iterator.next indicates that the next step, if you do not understand generators is okay, you can ignore it directly to learn Await/async.

Generators
function request (URL) {
    ajax (URL, (response) => {
        Iterator.next (json.parse (response));
    } );
}

function *main () {
    //Fetch product data let data
    = Yield request (' Products.json ');

    Get user Data let
    users = Yield request (' Users.json ');

    Get Comment data let products
    = Yield request (' Comments.json ');

    Console.log (' generator/products >>> ', products);
    Console.log (' Generator/users >>> ', users);
    Console.log (' generator/comments >>> ', comments);
}

var iterator = main ();
Iterator.next ();
Fort's friend Await/async.

Used in conjunction with Promise

Encapsulates Ajax, returns a Promise
function requestp (URL) {return
    new Promise (function (resolve, reject) {
        Ajax (URL, Response) => {
            Resolve (Json.parse (response));

});} (Async () => {
    //access to product data let:
    await REQUESTP (' Products.json ');

     Get user Data let
    users = await requestp (' Users.json ');

     Get comment Data let's products
    = await requestp (' Comments.json ');

    Console.log (' ES7 async/products >>> ', products);
    Console.log (' ES7 async/users >>> ', users);
    Console.log (' ES7 async/comments >>> ', comments);
} ());

Used in conjunction with the Fetch API:

 (Async () => {//async/await using the Fetch API try {//Get product data let products = await fetch (' PR

        Oducts.json ');

        Parsing products Let parsedproducts = await Products.json ();

        Get user Data let users = await fetch (' Users.json ');

        Parsing users let Parsedusers = await Users.json ();

        Get Comment data Let comments = await fetch (' Comments.json ');


        Parsing comments Let parsedcomments = await Comments.json ();
        Console.log (' ES7 async+fetch/products >>> ', parsedproducts);
        Console.log (' ES7 async+fetch/users >>> ', parsedusers);


    Console.log (' ES7 async+fetch/comments >>> ', parsedcomments);
    catch (Error) {Console.log (error); }
}());

Combine Fetch again

(Async () => {let
    paralleldatafetch = await* [
        await fetch (' Products.json ')]. JSON (),
        (await fetch (' Users.json ')). JSON (),
        (await fetch (' Comments.json ')). JSON ()
    ];
    Console.log (' Async parallel+fetch >>> ', paralleldatafetch);
} ());

Using Await/async to solve asynchronous code with synchronized thinking is very cool and refreshing.

Reference [Original]:https://github.com/jaydson/es ...

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.