Created
March 30, 2020 17:58
-
-
Save herrera-ignacio/4d63f6116c793381fe8fc9f67a894b95 to your computer and use it in GitHub Desktop.
Playing with Promises in Javascript
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
// Promises javascript example | |
// Maximize asynchronous benefits! | |
const makePromise = (num) => () => new Promise((resolve, reject) => { | |
return setTimeout(() => { | |
console.log(num) | |
resolve(); | |
}, 1000 * Math.floor(3 * Math.random())) | |
}); | |
const promises = [makePromise(1), makePromise(2), makePromise(3), makePromise(4)] | |
// Run promises asynchronously as an example | |
// You'll see they end in different orders each time | |
// promises.map((p) => p()) | |
// SEQUENTIAL RUN | |
promises.reduce((res, nextPromise) => res | |
.then(() => nextPromise()) | |
, Promise.resolve()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment