有没有办法减慢async-await for-loop/forEach中的fetch调用以避免每秒API配额?

E_C*_*E_C 1 javascript fetch async-await

我正在开发一个应用程序,需要调用foursquare的地方api,它具有每秒2次调用的配额.应用程序拉出一个地方列表,然后必须单独调用每个地方的图片.我试图在forEach函数和For-In函数中执行此操作.我已经尝试了所有我能想到的东西,并找到了研究,使这项工作(从在各种情况下使用setTimeout,到创建包含超时的承诺,并以多种不同的方式结合tehm),但我一直无法找到任何解决方案协助我的特定异步/等待获取情况.

要清楚 - 应用程序是可操作的,我的"其他"声明正在进行,但是else语句正在进行,因为我超过了每秒的配额 - 所以,代码就在那里,并且工作,我只是想能够运行照片而不是通用图标.如果我等待足够长的时间,我可以让照片工作,好像服务器忘了一秒钟.但我的每日总配额远远超过我在开发环境中可以达到的任何东西,所以这必须是让我遇到麻烦的原因!

如果有人可以提供帮助,我将非常感激!

const renderVenues = (venues) => {
  for(let i=0; i < $venueDivs.length; i++){
    const $venue = $venueDivs[i];
    const venue = venues[i];
    let newUrl = `https://api.foursquare.com/v2/venues/${venue.id}/photos?client_id=${clientId}&client_secret=${clientSecret}&v=20190202`;
    const getPics = async () =>{
      try{
      const picResp = await fetch(newUrl);
      if(picResp.ok){
        const picJson = await picResp.json();
        const photo = picJson.response.photos.items[0];
        const venueImgSrc = `${photo.prefix}300x300${photo.suffix}`;
        let venueContent = `<h2>${venue.name}</h2><h4 style='padding-		top:15px'>${venue.categories[0].name}</h4>
        <img class="venueimage" src="${venueImgSrc}"/>
        <h3 style='padding-top:5px'>Address:</h3>
        <p>${venue.location.address}</p>
        <p>${venue.location.city}, ${venue.location.state}</p>
        <p>${venue.location.country}</p>`;
        $venue.append(venueContent);
      } else{
          const venueIcon = venue.categories[0].icon;
          const venueImgSrc = `${venueIcon.prefix}bg_64${venueIcon.suffix}`;
          let venueContent = `<h2>${venue.name}</h2><h4 style='padding-top:15px'>${venue.categories[0].name}</h4>
    <img class="venueimage" src="${venueImgSrc}"/>
    <h3 style='padding-top:5px'>Address:</h3>
    <p>${venue.location.address}</p>
    <p>${venue.location.city}, ${venue.location.state}</p>
    <p>${venue.location.country}</p>`;
      $venue.append(venueContent);
      }
    }
    catch(error){
        console.log(error)
        alert(error)
      }
    }
    getPics();
  }

  $destination.append(`<h2>${venues[0].location.city}, ${venues[0].location.state}</h2>`);
}

//and then below, I execute the promise(s) that this is included with.

getVenues().then(venues =>
    renderVenues(venues)
  )
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 5

在每次迭代中,你可以awaitPromise用0.6秒后决定:

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
const renderVenues = async (venues) => {
  for(let i=0; i < $venueDivs.length; i++){
    // ...
    await getPics();
    // no need for a trailing delay after all requests are complete:
    if (i !== $venueDivs.length - 1) {
      await delay(600);
    }
  }
  $destination.append(...)
};
Run Code Online (Sandbox Code Playgroud)