Last active
August 20, 2019 21:57
-
-
Save SekiT/9ea2f76a089d04bd228d64aa6ee712e8 to your computer and use it in GitHub Desktop.
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
// Promise that resolves with n, after n seconds | |
const wait = n => new Promise(resolve => setTimeout(() => resolve(n), n * 1000)) | |
// Promise that rejects with n, after n seconds | |
const failAfter = n => new Promise((_, reject) => setTimeout(() => reject(n), n * 1000)) | |
Promise.all([wait(1), wait(2), wait(3)]).then(console.log) | |
// => Resolves with [1, 2, 3] after 3 seconds | |
Promise.all([wait(1), failAfter(2), wait(3)]).catch(console.log) | |
// => Rejects with 2 after 2 seconds | |
// (ReadonlyArray<() => Promise<T>>) => Promise<ReadonlyArray<T>> | |
const sequence = promiseCreators => | |
promiseCreators.reduce( | |
(acc, creator) => acc.then(accumulatedResult => creator().then(newResult => [...accumulatedResult, newResult])), | |
Promise.resolve([]) | |
) | |
sequence([() => wait(1), () => wait(2), () => wait(3)]).then(console.log) | |
// => Resolves with [1, 2, 3] after 6 seconds | |
sequence([() => wait(1), () => failAfter(2), () => wait(3)).catch(console.log) | |
// => Rejects with 2 after 3 seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment