我写了下面的代码然后意识到它正在提前解决(在所有 promise 解决之前记录):
readDirPromise
.then(categoriseFiles)
.then(({movies, series}) => ({
movies: Promise.all(movies.map(movieTasks)),
series: Promise.all(series.map(seriesTasks))
}))
.then((res) => {
console.log('🦄 done!', res)
})
我已经设法重写它以按正确的顺序解析:
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)
})
但我忍不住想...有没有更简洁、更可扩展的方法?
最佳答案
你可以让系列步骤独立于电影步骤运行(而不是一个接一个地阻塞),方法是将它们都包装在 Promise.all
的另一层中,作为一个元组返回然后你可以解构并重组为你想要的对象:
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)
})
关于javascript - JS promise : is there a neat way to resolve multiple promises as object properties?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43091961/