Skip to content

Instantly share code, notes, and snippets.

@mostafahussein
Forked from calendee/testChainedPromise.js
Created January 7, 2016 18:34
Show Gist options
  • Save mostafahussein/73d5672c8c2a2755bc84 to your computer and use it in GitHub Desktop.
Save mostafahussein/73d5672c8c2a2755bc84 to your computer and use it in GitHub Desktop.
A simple example of chained promises using Q promise library.
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