Created
July 1, 2017 23:00
-
-
Save flipsi/e47d987740d6b4c016f90192519be39d to your computer and use it in GitHub Desktop.
Javascript Promises Chained
This file contains hidden or 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
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