Promise of ES6 new features and promise of es6 New Features

Source: Internet
Author: User

Promise of ES6 new features and promise of es6 New Features

The promise concept is introduced in the new ES6 to make the callback more elegant. Layer-by-layer nested callback will make javascript less aesthetic and readable. At the same time, javascript also recommends using a chained method to write function calls. So Promise came into being. Promise is the meaning of commitment, and a new Promise is the creation of a commitment. When creating a new commitment, you need to do two things:

  1. specify the tasks to be completed

2.Set the criteria for commitment implementation

Next we will define a commitment:

1. Promised content:"Obtain data of data. php",

2.Whether or not the commitment is implemented is judged as follows:"Whether to obtain data of data. php"

Here we will use the jQuery. ajax () method, which will make our code simple and refined.

var http = {    get: function(url) {        var promise = new Promise(function(resolve, reject) {            $.ajax({                url: url,                method: 'get',                success: function(data) {                    resolve(data);                },                error: function(xhr, statusText) {                    reject(statusText);                }            });        });        return promise;    }};http.get('data.php').then(function(data) {    document.write(data);}, function(err) {    document.write(err);});

Here is the obtained data value

/* Data. php file */<? Phpecho '{"name": "Tom", "age": "22 "}';

In an http request, we define a get method. In the get method, we define a promise object, instead of directly obtaining the desired data using ajax, in this get method, we finally get a promise object. For this kind of operation that needs to be waited, we use promise to process it and return it to the main thread as a promise object, instead of the final data, this is a promise of the delay program to the main program. The main thread can obtain data or handle Errors Based on the returned promise object. This makes asynchronous processing elegant and simple.

In jQuery. ajax (), we use two methods to determineWhether our commitment has been fulfilled,They are the resove and reject methods, if jQuery. if ajax () executes success and the returned data contains data, we determine that this commitment has been implemented (fulfilled) and call the resolve method. If jQuery. ajax () executes error, we determine that this commitment is denied (rejected) and call the reject method.

What operations are performed by the resove and reject methods respectively? We need to start with the structure of the constructor Promise. The structure of the constructor Promise is roughly as follows:

/* Code used to describe thinking */function Promise (executor) {// There are three states: pending (preparation), fulfilled (Completion), rejected (rejection) this. promiseStatus = 'Pending'; // used to store the returned data this. promiseValue; // complete var resolve = function (reson) {}; // reject var reject = function (reson ){};... // start executing the Promise executor (resolve, reject);} Promise. prototype. then = function () {}; Promise. prototype. chain = function () {}; Promise. prototype. catch = function (){};...

  

PromiseStatus:Used to record three States of the Promise object. The three States are:
Pending:TBD status. The status of the Promise object that has just been initialized
Fulfilled:Completion status, which indicates that the task has been completed.
Rejected:Rejected status, the status of commitment completion failure
The initial state of Promise is pending. Then, the PromiseStatus value will be changed even if the commitment is completed.

PromiseStatus:Used to record returned data or errors. When the commitment is completed, the returned data is assigned to PromiseStatus. If the commitment fails, the cause of the failure is also assigned to this variable.

Resolve () and reject ():The Promise constructor has two closure functions: resolve () and reject (). When a new Promise is created, the executor will be passed on ). This executor is a function. In the constructor of Promise, it will be passed in two parameters. These two parameters are the resolve () and reject () functions of our two closures (), so that you can determine in executor whether your commitment has been fulfilled.

Executor ():The Code executed in the executor () function is the completion of the subroutine. If resolve () is called in the executor () function, resolve () changes Promise object state PromiseStatus to fulfilled and resolve (value) the value in is assigned to the PromiseValue of the Promise object. Then, execute the callback functions in the callback chain consisting of the then () method in sequence. Similarly, the process of calling reject () in executor () is similar. The call process is as follows:

 
/* Code used to describe thinking */executor (resolve, reject ){... resolve (value );...}... resolve (value) {PromiseStatus = 'fullfiled'; PromiseValue = value ;... // call the callback function in the callback chain}

  

Then (onFulfilled, onRejected ):This method adds the onFulfilled () function and onRejected () function to the callback chain of the Promise object. A callback chain is like a queue composed of function groups. Each function group is composed of at least one function (onFulfilled (), onRejected (), onFulfilled (), and onRejected ()). When the resolve () or reject () method is executed, the callback function in the callback chain is called in sequence based on the status of PromiseStatus.

OnFulfilled (value) and onRejected (reason ):The real parameters of value and reason are both PromiseValue. It is worth noting that if the return value in the onFulfilled (value) and onRejected (reason) callback functions is not a Promise object, the return value will be assigned to PromiseValue, it is used as real parameters in onFulfilled (value) and onRejected (reason) of the next then.However, if the returned value is a Promise object, the remaining callback chain constructed by then () will be transferred to the new Promise object and complete the call.

If the onRejected (reason) callback function is executed in the first then () and no value is returned, the next then () the onFulfilled (value) method is called instead of onRejected (reason ). Because no error or exception occurs when executing the onRejected (reason) callback function of the previous then (), the PromiseStatus status is changed to fulfilled. To avoid this problem, we can return a Promise object and reject () in onRejected (reson (). The Code is as follows:

var http = {    get: function(url) {        var promise = new Promise(function(resolve, reject) {            $.ajax({                url: url,                method: 'get',                success: function(data) {                    resolve(data);                },                error: function(xhr, statusText) {                    reject(statusText);                }            });        });        return promise;    }};http.get('solve.php').then(function(data) {    return data;}, function(err) {    return Promise.reject('Sorry, file not Found.');}).then(function(data) {    document.write(data);}, function(err) {    document.write(err);});

The Promise. reject () method returns a Promise object to be reject (), so that we can continue with the onRejected (reason) method in the next then.

 

This is the end of promise, refer to the thinking of the Taoist friends, the original link: http://www.jianshu.com/p/87183851756f

 

Related Article

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.