Skip to content

Instantly share code, notes, and snippets.

@sarunast
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sarunast/c23c316bdbd06d4cec5c to your computer and use it in GitHub Desktop.
Save sarunast/c23c316bdbd06d4cec5c to your computer and use it in GitHub Desktop.
Promise chaining example (promised-io)
var Deferred = require("promised-io/promise").Deferred;
// 1st function with promise
var function1 = function(bool){
var deferred = new Deferred();
//add timeout for fun
setTimeout(function(){
bool ? deferred.resolve('yay1') : deferred.reject('no1');
}, 300);
return deferred.promise;
};
// 2nd function with promise
var function2 = function(bool){
var deferred = new Deferred();
bool ? deferred.resolve('yay2') : deferred.reject('no2');
return deferred.promise;
};
function1(true).then(function (first) {
console.log(first);
// To chain promises you need to return other promise here
return function2(false);
}).then(function (second) {
console.log(second);
}, function (err) {
// Here we get error from both chained functions
console.log(err)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment