The Promise in JavaScript

Source: Internet
Author: User

Promise Definition

Promise is one of COMMONJS's specifications, including methods such as Resolve,reject,done,fail,then, which can help us control the flow of code and avoid multi-layered nesting of functions. Async is becoming more and more important in web development, and for developers, the programming of J-non-linear execution can be difficult for developers to control, and promise allows us to better control the execution of code, and the popular JS libraries such as jquery have already implemented this object, Now the ES6 has been natively implemented promise.

Scenario Description:

There are times when you need to send two asynchronous requests, and the second request uses the first data that returns the result:

Ajax ({        url:url1,        function(data) {            ajax ({                url:url2,                data:data,                 function() {                }})            ;}        );

Tidy up a little bit and wrap the latter call into a function, which is Jiangzi drop:

    function A () {        ajax ({            url:url1,            function(data) {                B (data);            }        });    }     function B (data) {        ajax ({            url:url2,            function(data) {                ...            }        });    }

If the asynchronous request C also needs to use the result of B, it also needs a layer. If you need a lot of layers, your code will be less readable and you won't be looking directly at it. So there is the promise. With the promise, the code is Jiangzi:

New Promise (A). Done (B);

It's very refreshing and dry.

ES6 has implemented the promise, but can also write a Promise object:

Use two arrays (Donelist and faillist) to store the callback function queue when successful and the callback function queue when it fails.

Methods and properties of this object:

1.state: The current execution state, with pending, resolved, rejected3 kind of value

2.done: Add a successful callback function to the Donelist

3.then: Add callback functions to Donelist and faillist respectively

4.always: Add a callback function that will be called regardless of success or failure

5.resolve: Changes the state to resolved and triggers all successful callback functions for the binding

6.reject: Changes the state to rejected and triggers all failed callback functions for the binding

7.when: The parameter is multiple asynchronous or deferred functions, the return value is a promise redemption, when all functions are executed successfully, the resolve method of the object is executed, and the Reject method of the object is executed.

Specific implementation:

varPromise =function() {     This. donelist = [];  This. faillist = [];  This. state = ' pending ';}; Promise.prototype={constructor:' Promise ', Resolve:function() {         This. state = ' Resolved '; varList = This. donelist;  for(vari = 0, len = list.length; i < Len; i++) {list[0].call ( This);        List.shift (); }}, Reject:function() {         This. State = ' Rejected '; varList = This. faillist;  for(vari = 0, len = list.length; i < Len; i++) {list[0].call ( This);        List.shift (); }}, Done:function(func) {if(typeofFunc = = = ' function ') {             This. Donelist.push (func); }        return  This; }, fail:function(func) {if(typeofFunc = = = ' function ') {             This. Faillist.push (func); }        return  This; }, then:function(Donefn, FAILFN) { This. Done (DONEFN). Fail (FAILFN); return  This; }, always:function(FN) { This. Done (FN). Fail (FN); return  This; }};

This does not support chained calls, and can be used to support chained calls:

varMpromise =function(func) { This. donelist = [];  This. state = ' pending '; Func ( This. Resolve.bind ( This));  This. Self = This;} Mpromise.prototype={resolve:function(){        varargs = Arguments[0];  while(true) {args=[args];  This. Lastargs =args; if( This. Donelist.length = = 0 ){                 This. State = ' Done ';  Break; } args= This. Donelist.shift (). Apply ( This, args); if(argsinstanceofmpromise) {                 This. Self =args; Args.donelist= Args.doneList.concat ( This. Donelist.slice (0));  This. State = ' Done ';  This. donelist.length = 0;  Break; }}}, then:function(callback) { This. Donelist.push (callback); if( This. state = = ' Done ' ){             This. state = ' pending ';  This. resolve.apply ( This, This. Lastargs); }        return  This. Self; }}

Es6-promise

ES6 provides native Promise objects: Syntactically speaking, Promise is an object from which you can get messages for asynchronous operations.

Basic usage:

The Promise object in ES6 is a constructor that is used to generate an promise instance.

var New Promise (function(resolve, Reject) {  //  ... some code  if (/ **/) {    Resolve (value)  ; Else {    reject (error);  }});

The Promise object receives a function as a parameter, and the two parameters of the function are resolve and reject, which are provided by the JavaScript engine and are not deployed on their own.

The purpose of the Resolve function is to change the state of the Promise object from "unfinished" to "successful" (that is, from pending to resolved), to invoke when the asynchronous operation succeeds, and to pass the result of the asynchronous operation as a parameter; the function of the Reject function is to Passes the state of the promise object from incomplete to failed (that is, from pending to rejected), when the asynchronous operation fails, and the error reported by the asynchronous operation as a parameter.

After the promise instance is generated, you can use the then method to specify the callback function for the resolved state and the Reject State, respectively.

Promise.then (function(value) {  //  successfunction(error) {   // failure});

The then method can accept two callback functions as arguments. The first callback function is called when the state of the Promise object becomes resolved, and the second callback function is called when the state of the Promise object changes to reject. Where the second function is optional and not necessarily provided. Both of these functions accept the value of the Promise object as an argument.

The Promise in JavaScript

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.