Created
August 3, 2016 00:59
-
-
Save Mike-Dunton/18344bab5afab59b0a13da2f050f6de8 to your computer and use it in GitHub Desktop.
Example using q promise.
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 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