Javascript Promise Learning (middle)

Source: Internet
Author: User

After a few days, the promise have a little more understanding.

Recently developed with Angularjs, so studied its $q

function is not very powerful, is a simplified version of the Q.js

Reference to the source code, but my grade is much worse ...

As a study, I rewrote an article myself.

This time is quite neat. The code is less.

$q =function(ASYNCFN) {vardefer =NewDeferred ();            ASYNCFN (Defer.resolve.bind (defer), Defer.reject.bind (defer)); returndefer.promise;        }; $q. Defer=function () {            return NewDeferred ();        }; $q. Reject=function(reason) {vardefer =NewDeferred ();            Defer.reject (reason); returndefer.promise;        }; $q. All=function(values) {vardefer =NewDeferred (); varFinaldatas = []; varCount = 0; Values.foreach (function(value, i) {count++; $q. When (value,function(data) {Finaldatas[i]= data;//load directly by index without ordering separately                    if(--count = = 0) {//One + + one--Cancel each other outdefer.resolve (Finaldatas); }                }, function(reason) {defer.reject (reason);            });            }); returndefer.promise;        }; $q. when=function(value, onfulfilled, onrejected, onnotify) {if(ValueinstanceofPromise)returnValue.then (onfulfilled, onrejected, onnotify); vardefer =NewDeferred ();            Defer.resolve (value); returnDefer.promise.then (onfulfilled, onrejected, onnotify);        }; functionDeferred () { This. Promise =NewPromise (); } Deferred.prototype= {            //resolve reject is almost the same, notify will not be deleted after the callResolvefunction(data) {varPromise = This. Promise; //to delay execution and prevent the then method from setting a callback, you want to resolve the situationSetTimeout (function() {promise.states= "fulfilled";                Promise._processcallback (data); }, 0); }, Reject:function(reason) {varPromise = This. Promise; SetTimeout (function() {promise.states= "Rejected";                Promise._processcallback (reason); }, 0); }, notify:function(data) {varPromise = This. Promise; SetTimeout (function() {promise.states= "Notify"; Promise._processcallback (data,true); }, 0); }, constructor:deferred}//Mainis to save defer, do promise.        functionCallback (Defer, onfulfilled, onrejected, onnotify) { This. defer =defer;  This. onfulfilled =onfulfilled;  This. onrejected =onrejected;  This. onnotify =onnotify; }        functionPromise () { This. states = "Pending";  This. Value =undefined;  This. Reason =undefined;  This. _callbacks = []; } Promise.prototype={then:function(onfulfilled, onrejected, onnotify) {//collect the callbacks, and if states not wait, leave immediately.                vardefer =NewDeferred ();  This. _callbacks.push (NewCallback (Defer, onfulfilled, onrejected, onnotify)); if( This. States!== "Pending") {                    vardata = ( This. states = = = "fulfilled")? This. Value: This. Reason;  This. _processcallback (data); }                returndefer.promise; },            "Catch":function(onrejected) {return  This. Then (NULL, onrejected); },            ' Finally ':function(cleanup) {return  This. Then (cleanup, cleanup); }, _processcallback:function(data, is_keepcallback) {//The data here does not accept promise, lazy did not do. Haha                varPromise = This; if( This. states = = = "Pending")return; varstates = ("on-" + This. States). Tocamelcase (); varPromisecallbacks = This. _callbacks; varLength =promisecallbacks.length;  for(vari = 0, L = promisecallbacks.length; I < L; i++) {                                      varcallback = (is_keepcallback)?Promisecallbacks[i]: Promisecallbacks.shift (); vardefer =Callback.defer; if(G.isfunction (Callback[states])) {//to do error handling.                        Try {                            //Call Callback,                            varReturnValue =Callback[states] (data); //if it's promise, then it's a big move, connecting promise to the past .                            if(returnvalueinstanceofPromise) {Returnvalue.then (Defer.resolve.bind (defer), Defer.reject.bi nd (defer));//bind is used here because the resolve needs to refer to this                            }                            Else {                                //if it's not, the value is passed to the next promise.defer.resolve (returnvalue); }                                                   }                        Catch(e) {defer.reject (e); }                    }                    Else {                        //data is not a function, it goes straight down .defer.resolve (data); }}}, constructor:promise}

Javascript Promise Learning (middle)

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.