angular 之 $q

对于 $q 这个服务。

提供如下方法:

defer       

var defer = function(){
    return Deferred();
}

对于defer ,拥有的方法有。

var defer = $q.defer();    // defer 对象。

defer.resolve(value)  // 

defer.reject(reason)   // 

defer.notify(value)    // 

var promise = defer.promise;   //////  promise 对象。

promise.then(successCallback,errorCallback,notifyCallback);

promise[catch](errorCallback);

promise[finally](callback,notifyCallback)


reject    

var reject = function(reason){
    var result = new Deferred();
    result.reject(reason);
    return result.promise;
}

when

var when = function(value,callback,errback,progressBack){
    var result = new Deferred();
    result.resolve(value);
    return result.promise.then(callback,errback,progressBack);
}

resolve

var resolve = when

all

var all = function(promises){
    var deferred = new Deferred();
    var counter = 0;
    var results = isArray(promises)? []:{};
    
    forEach(promises,function(promise,key){
        counter++;
        when(promise).then(
            function(value){
                if(results.hasOwnProperty(key)) return ;
                
                results[key] = value;
                
                if(!(--counter)) deferred.resolve(results);
            },
            function(reason){
                if(results.hasOwnProperty(key)) return;
                deferred.reject(reason);
            }
        );
    });
    
    if(counter === 0){
        deferred.resolve(reaults);
    }
    
    return deferred.promise;
}

    对于q 方法

var $Q = function Q(resolver){
    if(!(this instanceof Q)){
        return new Q(resolver);
    }
    
    var deferred = new Deferred();
    
    function resolveFn(value){
        deferred.resolve(value);
    }
    
    function rejectFn(reason){
        deferred.inject(reason);        
    }
    
    resolver(resolveFn,rejectFn);
    
    return deferred.promise;
}




你可能感兴趣的:(Angular)