Skip to content

Instantly share code, notes, and snippets.

@kouks
Last active February 24, 2019 17:56
Show Gist options
  • Select an option

  • Save kouks/266888695364f82dec0f149ce6128407 to your computer and use it in GitHub Desktop.

Select an option

Save kouks/266888695364f82dec0f149ce6128407 to your computer and use it in GitHub Desktop.
Resolve an array of JS promises one after another - one liner
// Example data.
const data = [1, 2, 3]
const fn = async a => a * a
// If we care about errors.
data.reduce((carry, item) => carry.then(() => fn(item)), Promise.resolve())
.catch(console.error)
.then(() => { ... })
// If we don't care.
data.reduce((carry, item) => carry.then(() => fn(item), () => {}), Promise.resolve())
.then(() => { ... })
// You can also pass the argument around.
data.reduce((carry, item) => carry.then(res => fn(res + item)), Promise.resolve(1))
.then(res => { ... })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment