Search code examples
javascriptasynchronousfetch

How to async await in promise.all


i wnna make an API thing that load list of pokemons and when it's image. got the list and wanna make sure the sequence on pictures will be correct for this i console.log the same names. and sequence is wrong. tried some async await in diff places and can't figure out how to get proper order 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)
    })
}

Solution

  • const results = await Promise.all(arrForFetch)
    // do something with results array
    

    Your issue is that file.json() is async so needs to be returned from the loop as another Promise all, or awaited in the loop. You can map the promises.

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