首页 > 解决方案 > 如何在 promise.all 中异步等待

问题描述

我想制作一个 API 东西来加载口袋妖怪列表以及它的图像。得到列表,并想确保图片上的顺序对于这个 i 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)
    })
}

标签: javascriptasynchronousfetch

解决方案


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"))


推荐阅读