Last active
April 9, 2020 00:41
-
-
Save crutchcorn/d7a2c1f51e5bc34e7930111f8f1aa2b6 to your computer and use it in GitHub Desktop.
An explanation of Promise.all that includes mention of mapping through them
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
// This is a simple promise that will return a promise that resolves after the num | |
const getPromiseTimeout = num => new Promise(resolve => { | |
setTimeout(() => resolve(num), num); | |
}) | |
const timeouts = [getPromiseTimeout(100), getPromiseTimeout(300), getPromiseTimeout(200)]; | |
// Promise.all will run these promises in whatever order it wants, but will resolve | |
// with the same order they were passed in on. They run in 'parallel' | |
// Will console.log(100, 300, 200) in the same order as the order above | |
Promise.all(timeouts).then((arrRestults) => console.log(arrRestults)); | |
// Because Promise.all returns a promise itself, you can chain them together | |
Promise.all([ | |
Promise.all([ | |
getPromiseTimeout(300) | |
]) | |
]).then(arrVal => { | |
console.log(arrVal); // [[300]] | |
}) | |
// As such, you can have functions that use Promise.all and return a single promise | |
const getTimeoutTimes = (times) => { | |
const timess = times.map(time => getPromiseTimeout(time)); | |
return Promise.all(timess); | |
} | |
Promise.all([ | |
getTimeoutTimes([100, 300, 500]), | |
getTimeoutTimes([200, 400, 600]) | |
]).then(arrVal => { | |
console.log(arrVal); // [[100, 300, 500], [200, 400, 600]] | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment