skip to Main Content

I am trying to fetch json data from the unsplash api inside of a for loop but it will not sync with the loop.

async function myfunction(){

for (x=0;x<=c.length-1; x++){

     await 

  fetch('https://api.unsplash.com/search/photos? 
   client_id=123;query=' +   
      c[x].value).then(function(response){

         response.json().then(function(data) {
               //out of sync with for loop
         }
      });
   });  
}

}

2

Answers


  1. Try this way :

    async function fetchData() {
        let promises = [];
    
        for (let x = 0; x <= c.length - 1; x++) {
            let url = 'https://api.unsplash.com/search/photos?client_id=123&query=' + c[x].value;
            promises.push(fetch(url).then(response => response.json()));
        }
    
        let results = await Promise.all(promises);
    
        // Process results here
        results.forEach(data => {
            // Do something with each data object
        });
    }
    
    fetchData();
    
    Login or Signup to reply.
  2. You’re mixing both async/await syntax with good old Promise#then (but without returning the promise to properly chain).

    You could try using only async/await:

    async function myfunction(){
      for (let x=0;x<=c.length-1; x++){
        const response = await fetch('https://api.unsplash.com/search/photos?client_id=123;query=' + c[x].value);
        const data = await response.json();
        // do something with data
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search