Last active
August 29, 2015 14:15
-
-
Save sarunast/c23c316bdbd06d4cec5c to your computer and use it in GitHub Desktop.
Promise chaining example (promised-io)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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