-
-
Save mostafahussein/73d5672c8c2a2755bc84 to your computer and use it in GitHub Desktop.
A simple example of chained promises using Q promise library.
This file contains hidden or 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 Q = require("q"); | |
var slowFunction1 = function( myObject ) { | |
console.log("\nRunning slowFunction1"); | |
console.log(myObject); | |
var deferred = Q.defer(); | |
setTimeout( function() { | |
console.log("slowFunction1 is resolving!"); | |
myObject.slowFunction1Processed = true; | |
deferred.resolve( myObject ); | |
}, 1500); | |
return deferred.promise; | |
}; | |
var slowFunction2 = function( myObject ) { | |
console.log("\nRunning slowFunction2"); | |
console.log(myObject); | |
var deferred = Q.defer(); | |
setTimeout( function() { | |
console.log("slowFunction2 is resolving!") | |
myObject.slowFunction2Processed = true; | |
deferred.resolve( myObject ); | |
}, 1500); | |
return deferred.promise; | |
}; | |
var slowFunction3 = function( myObject ) { | |
console.log("\nRunning slowFunction3"); | |
console.log(myObject); | |
var deferred = Q.defer(); | |
setTimeout( function() { | |
console.log("slowFunction3 is resolving!") | |
myObject.slowFunction3Processed = true; | |
deferred.resolve( myObject ); | |
}, 1500); | |
return deferred.promise; | |
}; | |
var processes = [ slowFunction1, slowFunction2, slowFunction3 ]; | |
var initialValue = { "stuff" : "it"}; | |
var getFinalResult = function() { | |
return processes.reduce( function( nextProcess, f ) { | |
return nextProcess.then(f); | |
}, Q(initialValue)); | |
}; | |
// | |
//getFinalResult().then( | |
// function( response) { | |
// console.log("\nFinished running !"); | |
// console.log(initialValue); | |
// | |
// console.log("\nHere is the returned response"); | |
// console.log(response); | |
// } | |
//); | |
var badSlowFunction = function( myObject ) { | |
console.log("\nRunning badSlowFunction"); | |
console.log(myObject); | |
var deferred = Q.defer(); | |
setTimeout( function() { | |
console.log("badSlowFunction is rejecting!") | |
myObject.badSlowFunction = true; | |
deferred.reject( myObject ); | |
}, 1500); | |
return deferred.promise; | |
}; | |
var processes = [ slowFunction1, badSlowFunction, slowFunction3 ]; | |
getFinalResult().then( | |
function( response) { | |
console.log("\nFinished running !"); | |
console.log(initialValue); | |
console.log("\nHere is the returned response"); | |
console.log(response); | |
}, | |
function( error ) { | |
console.log("Oh crappers! Something rejected!"); | |
console.log(error); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment