ES6/7/8 new features Promise,async,await,fetch take us away from the abyss of asynchronous callbacks

Source: Internet
Author: User

Promise:
Before ES6, if we need to do asynchronous processing in JS, most are solved by using callback functions, and if simple asynchronous processing, the callback function looks elegant, the force is still a bit high, but if there are many asynchronous operations, the callback nesting is very deep, the code will look particularly awkward , maintenance costs will also become higher this time ES6 bring promise this new feature, this method is a good solution to the deep-seated problem of asynchronous nesting, we write code can be similar to the way Linux streaming writing:
For example:

Flow (). Then (function (Success) {}). catch (function (error) {})

This kind of asynchronous operation looks very intuitive. Here is a complete proimise example

The function flow (flag) {
       //promise is a constructor that receives a callback function internally.
       //The callback function has two parameters inside, Reslove is called when execution succeeds, reject is the
       var promise = new Promise (function (Reslove,reject) of the failed invocation) {
          settimeout (function () {//Analog asynchronous Operation
               if (flag) {
                 reslove (true);/processing succeeded
               }else{
                 reject (false) processing failed
               }
          },5000)
       });
       return promise;
   }
   Flow returns a Promise object so that we can handle the asynchronous operation in the following way.
   //Call the function Flow
   (). Then (function (Success) {     
   }). catch (function (error) {
        //Process failure return
   });

Reslove representative processing success, corresponding to the subsequent Then,reject representative processing failure, corresponding to the following catch,resolve and reject can be a string, or an object, this value can be interpreted as a promise return value.
Promise Then,catch, there are all,race, specific how to use Find Niang. In fact, getting multiple promise objects at the same time returns a worthwhile operation.

See the use of the above promise, familiar with jquery driver is not a bit familiar with the hurrying feet. In fact, after the jquery1.5 version, $.ajax can use the flow of the above type of operation, began to gradually discard the callback method.

$.ajax ({}). then (function (Result) {}). Fail (function (error) {})

If you are still using the Success,error callback function in this way, hehe ....
Jquey uses a deferred way to achieve a similar promise function, after jquery1.7. Deferred was independently out,. Deferred was independently out,. The way deferred and promise are used is almost a mold:

function Runasync () {
    var def = $. Deferred ();
    Do some asynchronous operations
    settimeout (function () {//Simulate asynchronous Operation
        Def.resolve (' random data ');
    return def;
}
Runasync (). Then (function (data) {
    console.log (data)
});

Finish speaking proimise, now speaking async and await
async,await Grammar Sugar
Async and await are the new norms of ES7, and the two specifications can be seen as a group of conjoined twins who will be able to appear together to effect:

var stop= function (time) {return
    new Promise (function (resolve, reject) {
        settimeout (function () {
            Resolve ( );
        }, time);
    }
;

The var start = Async function () {
    //is used here as intuitive as the sync code
    console.log (' start ');
    var result = await stop (3000);
    Console.log (' end ');
Start ();

Note that await can only be used in async, otherwise it will not be effective. In fact, async and await combined to replace the promise of then and catch methods, the async of the lower Angyi function of the code from the asynchronous into a synchronous blocking, only if the number of lines defined by the await after the execution of the code will continue to execute, At the same time await also has a return value, and his return value in the example above is that the Resolve,reject value needs to be captured by the try {}catch (err) {}:

The var start = Async function () {
    //is used here as intuitive as the sync code
    console.log (' start ');
    try{
      await stop (3000);
    } catch (Err) {
      console.log (err);
    }
    Console.log (' end ');
Start ();

Await should be followed by a Promise object or fetch (later), otherwise the result will be a bit strange, I directly in the back of a settimeout, the result I am very puzzled, interested in the execution of the following two pieces of code, the result is beyond your imagination:

var Start1 = Async function () {
    //is used here as intuitive as the sync code
    console.log (' start ');
   var a = await settimeout (function () {Console.log ("---")},5000)
    console.log (' End ' +a);  Start1 (); Console.log ("----");
var Start2 = Async function () {
    //is used here as intuitive as the sync code
    console.log (' start ');
   var a = await settimeout (function () {Console.log ("---")},5000)
    console.log (' End ' +a);  Start (); Console.log ("----"); for (var i=0 i<10;i++) {console.log (i)}

In fact, personal feeling or like directly using promise to implement asynchronous operation, feeling async and await a bit to make things complicated. Of course, he was ES7 as a standard, but also a few norms, then he has a place to go. Especially if we sometimes need to sync the JS code.

Fetch:
This method is a new feature of the ES2017, this feature gives a traditional Ajax is dead feeling, in fact, its role is to replace the original browser XMLHttpRequest asynchronous request, we in the day-to-day development, the basic will not write their own xmlhttprequest, Mainly is too complex, are all the use has been encapsulated a variety of inserts, pieces of commonly used JQUERY,NPM package management tools also provide axios,request modules. With the fetch, we can quickly and easily implement the asynchronous request without these plug-ins:
GET Request:

var word = ' 123 ',
 url = ' https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd= ' +word+ ' &json=1&p=3 ';
Fetch (Url,{mode: "No-cors"}). Then (function (response) {return
 response;
}). Then (function (data) {
 console.log (data);
}). catch (function (e) {
 console.log ("Oops, Error");
});

POST request:

var headers = new headers ();
Headers.append ("Content-type", "Application/json;");
Fetch (URL, {method
 : ' Post ',
 headers:headers,
 body:JSON.stringify ({
 date: ' 2016-10-08 '
 ), Time: ' 15:16:00 '
 })
};

The above writing in fact and we commonly used Ajax plug-in writing is more like, but pay attention to the current raw fetch does not support JSONP request, if you need to implement JSONP, you need to install NPM package Fetchj-jsonp, use the way:

Fetchjsonp (URL, {
 timeout:3000,
 jsonpcallback: ' Callback '
}). Then (function (response) {
 Console.log (Response.json ());
catch (function (e) {
 console.log (e)
});

We can build our request headers with the new header:

var headers = new headers ();
Headers.append ("Content-type", "text/html");
Fetch (url,{
 headers:headers
});

The request headers can also be indexed:

var header = new Headers ({
 "Content-type": "Text/plain"
});
Console.log (Header.has ("Content-type")); True
Console.log (Header.has ("content-length"));//false

Fetch can set different modes to make the request valid. The pattern can be defined in the second parameter object of the Fetch method.
Through the use of the above fetch, you can see that he and promise use a very similar way, fetch actually return is a Promise object, async,await and fetch is perfect compatibility, we can use async, Await implements synchronization of code:

(Async () =>{
 try {Let
 res = await fetch (URL, {mode: ' No-cors '})//wait for Fetch to be resolve () to continue execution
 Console.log (res);
 catch (e) {
   console.log (e);
 }
}) ();

This article mainly combs the relationship between Promise,async,await,fetch, Primise is the foundation, Async,await,fetch is on the shoulder of promise.

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.