Skip to content

Instantly share code, notes, and snippets.

@Mike-Dunton
Created August 3, 2016 00:59
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 Mike-Dunton/18344bab5afab59b0a13da2f050f6de8 to your computer and use it in GitHub Desktop.
Save Mike-Dunton/18344bab5afab59b0a13da2f050f6de8 to your computer and use it in GitHub Desktop.
Example using q promise.
var qPromise = require('q')
var buildSecretTeller = function(promiseArray) {
return function(data){
var deferred = qPromise.defer();
promiseArray.push(deferred.promise)
var secretWaitLength = 2; //in seconds
console.log("I will tell you the secret in " + secretWaitLength + " seconds");
setTimeout(function(){
console.log("All done waiting, I am going to resolve my promise now and tell you the secret");
deferred.resolve( data + ", you are cute.");
}, secretWaitLength * 1000);
return;
}
}
var mainFunction = function() {
var promises = [];
var data = ["mike", "alli", "node"];
var secretTeller = buildSecretTeller(promises);
data.forEach(function(currentData){
secretTeller(currentData);
});
qPromise.allSettled(promises)
.then(function(results){
results.forEach(function (result) {
if (result.state === "fulfilled") {
console.log(result.value);
} else {
console.log(result.value);
}
});
});
};
mainFunction();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment