Parallel JS Promises Demo
Parallel JS Promises Demo
by Lou Mauget
HTML
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/q.js/1.0.1/q.js"></script>
<div class="container">
<h4>Parallel Promises</h4>
<div class="jumbotron" id='log'></div>
</div>
CSS
body {
background-color: LemonChiffon;
}
.jumbotron {
border: thin solid;
}
JavaScript
'use strict';
(function() {
var lineNum = 0,
badStuff = 'all that jazz',
promiseVals = ['To ', 'be, ', 'or ',
'not ', 'to ', 'be, ', 'that ',
'is ', 'the ', 'question.'
];
function log(strArg, color) {
var hstr,
prefix = strArg.length ? String(++lineNum) + '. ' : '',
str = prefix + strArg;
if (typeof document !== 'undefined') {
hstr = str;
if (typeof color === 'string') {
hstr = '<span style="color: ' + color + '; font-weight: 900;">' + str + '<span>';
}
document.getElementById('log').innerHTML += (hstr + '<br />');
};
console.log(str);
};
function makeAPromise(arg) {
var deferred = Q.defer();
console.log('makePromise: ' + arg);
// Simulate an async request that resovles the
// promise, or rejects it.
try {
window.setTimeout(function() {
if (arg === badStuff) {
deferred.reject("I don't like '" + arg + "'!");
} else {
deferred.resolve(arg);
}
}, 3000);
} catch (error) {
deferred.reject(error);
}
return deferred.promise;
};
function startParallelActions() {
var promises = [];
// Make an asynchronous action from each arg
promiseVals.forEach(function(value) {
promises.push(makeAPromise(value));
// Simulate error 10 * 5% of the time
if (Math.random() > 0.95) {
promises.push(makeAPromise(badStuff));
}
});
// Consolidate all promises into a promise of promises
return Q.all(promises);
};
// Returns a king promise that wraps an array of promises.
// Handle the resolution of the king promise within main().
(function main() {
var kingPromise = startParallelActions();
log(String(promiseVals.length) + ' promises pending. Wait for them, young Will Robinson.');
kingPromise.then(function(resp) {
var i = 0;
log('then(..) resp has ' + resp.length + ' items: ');
resp.forEach(function(item) {
...