Skip to content

Instantly share code, notes, and snippets.

@SekiT
Last active August 20, 2019 21:57
Show Gist options
  • Save SekiT/9ea2f76a089d04bd228d64aa6ee712e8 to your computer and use it in GitHub Desktop.
Save SekiT/9ea2f76a089d04bd228d64aa6ee712e8 to your computer and use it in GitHub Desktop.
// 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