如何在 promise.all 中异步等待

How to async await in promise.all

我想做一个 API 东西来加载口袋妖怪列表和图像。 拿到了清单,想确保图片上的顺序对于这个我 console.log 相同的名字是正确的。而且顺序错了。在不同的地方尝试了一些异步等待,但无法弄清楚如何获得正确的顺序 https://codepen.io/DeanWinchester88/pen/ExvxdxX

Promise.all(arrForFetch)
    .then(files => {
        files.forEach(file => {
            console.log("files", file)
            process(file.json())
        })
            .catch(err => console.log("tobie pizda ucziekaj"))
    })
let process = (prom) => {
    console.log(prom)
    prom.then(data => {
        console.log(data.name)
    })
}
const results = await Promise.all(arrForFetch)
// do something with results array

您的问题是 file.json() 是异步的,因此需要作为另一个 Promise all 从循环返回,或者在循环中等待。您可以映射承诺。

Promise.all(arrForFetch)
                 .then( files  =>{
                     const more = files.map(file=>file.json().then(process))
                     return Promise.all(more)
                   })
                  .catch(err  =>  console.log("tobie pizda ucziekaj"))


Promise.all(arrForFetch)
                 .then( async files  =>{
                     for(const i=0; i<files.length; i++){
                     console.log("files", files[i])
                     process(  await files[i].json() )
                     }
                   })
                  .catch(err  =>  console.log("tobie pizda ucziekaj"))