Promise object used to provide seperation of success and error resolution paths for async operations.

Example
var myFunc = function(){
    var promise = new Promise();
    //callback the promise after 10 Secs
    setTimeout(hitch(promise, "callback"), 10000);
    return promise.promise();
}
var myFunc2 = function(){
    var promises =[];
    for(var i = 0; i < 10; i++){
        promises.push(myFunc);
    }
    //create a new promise list with all 10 promises
    return new PromiseList(promises).promise();
}

myFunc.then(function(success){}, function(error){})
//chain promise operations
myFunc.chain(myfunc).then(function(success){}, function(error){})

myFunc2.then(function(success){}, function(error){})
//chain promise operations
myFunc2.chain(myfunc).then(function(success){}, function(error){})
            

Constructor

Defined promise.js Source
function (){
   this.__errorCbs = [];
   this.__cbs = [];
   this.callback = hitch(this, this.callback);
   this.errback = hitch(this, this.errback);
           
}
            

__resolve Function Private


Defined promise.js

Source
function (){
   var self = this;
   if (!self.__fired) {
       self.__fired = true;
       nextTick(function () {
           var cbs = self.__error ? self.__errorCbs : self.__cbs,
               res = self.__error || self.__results,
               i = -1, l = cbs.length;
           while (++i &lt; l) {
               spreadArgs(cbs[i], res);
           }
           self.__errorCbs.length = self.__cbs.length = 0;
           self = null;
       });
   }
           
}
    

addCallback Function Public


Defined promise.js

Add a callback to the callback chain of the promise

Arguments Returns Source
function (cb){
   if (cb) {
       if (isPromise(cb)) {
           cb = cb.callback;
       }
       if (this.__fired && this.__results) {
           this.__callNextTick(cb, this.__results);
       } else {
           this.__cbs.push(cb);
       }
   }
   return this;
           
}
    

addErrback Function Public


Defined promise.js

Add a callback to the errback chain of the promise

Arguments Returns Source
function (cb){
   if (cb) {
       if (isPromise(cb)) {
           cb = cb.errback;
       }
       if (this.__fired && this.__error) {
           this.__callNextTick(cb, this.__error);
       } else {
           this.__errorCbs.push(cb);
       }
   }
   return this;
           
}
    

both Function Public


Defined promise.js

Adds a callback or promise to be resolved for both success and error.

Arguments Returns Source
function (cb){
   this.addCallback(cb);
   if (isPromise(cb)) {
       this.addErrback(cb.callback);
   } else {
       this.addErrback(cb);
   }
   return this;
           
}
    

callback Function Public


Defined promise.js

When called all functions registered as callbacks are called with the passed in results.

Arguments Source
function (args){
   args = argsToArray(arguments);
   if (this.__fired) {
       throw new Error("Already fired!");
   }
   this.__results = args;
   this.__resolve();
   return this.promise();
           
}
    

chain Function Public


Defined promise.js

Call to chaining of promises

new Promise()
 .callback("hello")
 .chain(function(previousPromiseResults){
     return previousPromiseResults + " world";
}, errorHandler)
 .chain(function(previousPromiseResults){
   return when(dbCall());
 }).classic(function(err, results){
     //all promises are done
 });

You can also use static values

new Promise().callback()
    .chain("hello")
    .chain(function(prev){
        return prev + " world!"
    }).then(function(str){
        console.log(str); //"hello world!"
    });

If you do not provide an errback for each chain then it will be propogated to the final promise

new Promise()
    .chain(function(){
        return new comb.Promise().errback(new Error("error"));
    })
    .chain(function(){
        return prev + " world!"
    })
    .classic(function(err, str){
        console.log(err.message); //"error"
    });

Arguments Returns Source
function (callback,errback){
   var promise = new Promise(),
       self = this;
   function _errback(e) {
       if (isFunction(errback)) {
           try {
               var res = spreadArgs(errback, [e]);
               isPromiseLike(res) ? res.then(promise.callback, promise.errback) : promise.callback(res);
           } catch (e) {
               promise.errback(e);
           }
       } else {
           promise.errback(e);
       }
   }
   function _callback() {
       try {
           var res = isFunction(callback) ? spreadArgs(callback, arguments) : callback;
           if (isPromiseLike(res)) {
               res.then(promise.callback, _errback);
           } else {
               promise.callback(res);
               promise = null;
           }
           callback = res = null;
       } catch (e) {
           _errback(e);
       }
   }
   self.addCallback(_callback);
   self.addErrback(_errback);
   return promise.promise();
           
}
    

chainBoth Function Public


Defined promise.js

Applies the same function that returns a promise to both the callback and errback.

Arguments Returns Source
function (callback){
   var promise = new Promise();
   this.addCallback(function () {
       try {
           when(isFunction(callback) ? callback.apply(this, arguments) : callback).then(promise);
       } catch (e) {
           promise.errback(e);
       }
   });
   this.addErrback(function () {
       try {
           when(isFunction(callback) ? callback.apply(this, arguments) : callback).then(promise);
       } catch (e) {
           promise.errback(e);
       }
   });
   return promise.promise();
           
}
    

classic Function Public


Defined promise.js

Call this function as a classic node callback where the first argument will be an error, or null if no error occured. The other arugments will be the result from the promise.

Example
promise.classic(function(err, res){
     if(err){
         console.log(err);
     }else{
         console.log(res);
     }
});
        
Arguments Returns Source
function (cb){
   if ("function" === typeof cb) {
       this.addErrback(cb);
       this.addCallback(partial(cb, null));
   }
   return this;
           
}
    

errback Function Public


Defined promise.js

When called all functions registered as errbacks are called with the passed in error(s)

Arguments Source
function (args){
   if (this.__fired) {
       throw args || new Error("Already fired");
   }
   this.__error = argsToArray(arguments);
   this.__resolve();
   return this.promise();
           
}
    

promise Function Public


Defined promise.js

Creates an object to that contains methods to listen to resolution but not the "callback" or "errback" methods.

Example
var asyncMethod = function(){
    var ret = new comb.Promise();
    process.nextTick(ret.callback.bind(ret, "hello"));
    return ret.promise();
}

asyncMethod().callback() //throws error
        
Returns Source
function (){
   var ret = {
       promise: function () {
           return ret;
       }
   };
   var self = this;
   ret["chain"] = function () {
       return spreadArgs(self["chain"], arguments, self);
   };
   ret["chainBoth"] = function () {
       return spreadArgs(self["chainBoth"], arguments, self);
   };
   ret["addCallback"] = function () {
       spreadArgs(self["addCallback"], arguments, self);
       return ret;
   };
   ret["addErrback"] = function () {
       spreadArgs(self["addErrback"], arguments, self);
       return ret;
   };
   ret["then"] = function () {
       spreadArgs(self["then"], arguments, self);
       return ret;
   };
   ret["both"] = function () {
       spreadArgs(self["both"], arguments, self);
       return ret;
   };
   ret["classic"] = function () {
       spreadArgs(self["classic"], arguments, self);
       return ret;
   };
   return ret;
           
}
    

resolve Function Public


Defined promise.js

Resolved a promise using the node style callback.

Example
var promise = new Promise();
fs.readFile("file.txt", "utf8", promise.resolve.bind(promise));
promise.then(function(file){
    console.log(file);
});
        
Arguments Returns Source
function (err,args){
   if (err) {
       this.errback(err);
   } else {
       spreadArgs(this.callback, argsToArray(arguments, 1), this);
   }
   return this;
           
}
    

then Function Public


Defined promise.js

Call to specify action to take after promise completes or errors

Arguments Returns Source
function (callback,errback){
   if (isPromise(callback)) {
       errback = callback.errback;
       callback = callback.callback;
   }
   this.addCallback(callback);
   this.addErrback(errback);
   return this;
           
}
    

License

MIT https://github.com/C2FO/comb/raw/master/LICENSE

Meta