Search code examples
javascriptes6-promise

JS Promises: is there a neat way to resolve multiple promises as object properties?


I wrote the below code then realised it was resolving early (logging before all promises resolve):

readDirPromise
.then(categoriseFiles)
.then(({movies, series}) => ({
  movies: Promise.all(movies.map(movieTasks)),
  series: Promise.all(series.map(seriesTasks))
}))
.then((res) => {
  console.log('🦄 done!', res)
})

I've managed to rewrite it to resolve in the correct order:

readDirPromise
.then(categoriseFiles)
.then((cats) => Promise.all(cats.movies.map(movieTasks)).then((movies) => {
  cats.movies = movies
  return cats
}))
.then((cats) => Promise.all(cats.series.map(seriesTasks)).then((series) => {
  cats.series = series
  return cats
}))
.then((res) => {
  console.log('🦄 done!', res)
})

but I can't help but think... is there a neater, more extensible way?


Solution

  • You can make the series step run independently of the movies step (rather than blocking one after the other) by wrapping both of them in another layer of Promise.all, coming back as a tuple which you may then destructure and restructure into the object you want:

    readDirPromise
    .then(categoriseFiles)
    .then(({movies, series}) => Promise.all([
      Promise.all(movies.map(movieTasks)),
      Promise.all(series.map(seriesTasks))])
    .then(([movies, series]) => ({movies, series}))
    .then((res) => {
      console.log('🦄 done!', res)
    })