Fetch 不与 for 循环同步

问题描述 投票:0回答:2

我正在尝试从 for 循环内的 unsplash api 获取 json 数据,但它不会与循环同步。

异步函数 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
         }
      });
   });  
}

}

json asynchronous async-await fetch
2个回答
0
投票

试试这个方法:

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();

0
投票

您将两种

async/await
语法与良好的旧
Promise#then
混合在一起(但没有将承诺返回到正确的链)。

您可以尝试仅使用

async/await
:

async function myfunction(){
  for (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
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.