我正在开发一个需要调用 foursquare places api 的应用程序,它有每秒 2 次调用的配额。该应用程序提取地点列表,然后必须分别调用每个地点的图片。我试图在 forEach 函数和 For-In 函数中执行此操作。我已经尝试了我能想到的一切,并找到了研究来使这项工作(从在各种情况下使用 setTimeout,到创建包含超时的 promise ,并以许多不同的方式合并 tehm),但我一直无法找到任何解决方案协助处理我特定的异步/等待获取情况。
要清楚 - 应用程序是可操作的,我的“else”语句正在启动,但 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)
)
最佳答案
在每次迭代中,您可以await
Promise
在 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(...)
};
关于javascript - 有没有一种方法可以减慢 for-loop/forEach 中的 async-await fetch 调用以避免每秒 API 配额?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54546526/