gpt4 book ai didi

javascript - JS promise : is there a neat way to resolve multiple promises as object properties?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:40:59 24 4
gpt4 key购买 nike

我写了下面的代码然后意识到它正在提前解决(在所有 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com