Skip to content

Instantly share code, notes, and snippets.

@flipsi
Created July 1, 2017 23:00
Show Gist options
  • Save flipsi/e47d987740d6b4c016f90192519be39d to your computer and use it in GitHub Desktop.
Save flipsi/e47d987740d6b4c016f90192519be39d to your computer and use it in GitHub Desktop.
Javascript Promises Chained
function gimmeAPromiseWith(x) {
return new Promise(function(resolve, reject) {
console.log(`started calculation of ${x}`);
setTimeout(function() {
resolve(x);
console.log(`finished calculation of ${x}`);
}.bind(this), 10);
});
}
const whatwhatwhat = 'chain';
switch (whatwhatwhat) {
case 'parallel':
const promises = [
gimmeAPromiseWith(1),
gimmeAPromiseWith(2),
gimmeAPromiseWith(3),
];
Promise.all(promises).then(console.log); // [ 1, 2, 3 ]
Promise.all(promises).then(console.log); // [ 1, 2, 3 ]
break;
case 'chain':
const xs = [1, 2, 3];
xs.reduce(function(promise, x) {
return promise.then(v => gimmeAPromiseWith(x));
}, Promise.resolve()).then(console.log); // 3
break;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment