我有一个处于当前react状态的对象数组,我想迭代数组中的每个对象并获取一个想法,以便对每个对象发出请求,并从api获取信息以完成对象中缺少的数据。
当我运行该命令时,我得到了一个429错误,这意味着许多请求在他们有时间处理之前就被发送了。我试着用计时器,但那不起作用。我也尝试过使用useEffect,但是我遇到了同样的问题。我求助于回到最初的想法,这是一个for循环,但它打破了一切。
代码:
function buildCompleteProperties(){
for(let i = 0; i < propertyList.length; i++){
propertyOptions['params'] = {zpid: propertyList[i]['zpid']}
axios.request(propertyOptions).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
}
}最后,它显示了请求的第一个属性详细信息。下面是控制台的外观:
VM7363:1 GET https://zillow-com1.p.rapidapi.com/property?zpid=20471276 429 (Too Many Requests)
Error: Request failed with status code 429
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.onloadend (xhr.js:66)
VM7363:1 GET https://zillow-com1.p.rapidapi.com/property?zpid=20471276 429 (Too Many Requests)
Error: Request failed with status code 429
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.onloadend (xhr.js:66)
VM7363:1 GET https://zillow-com1.p.rapidapi.com/property?zpid=20471276 429 (Too Many Requests)
Error: Request failed with status code 429
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.onloadend (xhr.js:66)
VM7363:1 GET https://zillow-com1.p.rapidapi.com/property?zpid=20471276 429 (Too Many Requests)
Error: Request failed with status code 429
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.onloadend (xhr.js:66)
listingProvider: {…}, buildingPermits: null, propertyTaxRate: 0.77, contact_recipients: Array(1), solarPotential: {…}, …}
address:发布于 2021-11-04 20:47:27
当调用完成后,启动下一个调用。
function makeRequests() {
let i = 0;
function next() {
propertyOptions['params'] = {
zpid: propertyList[i]['zpid']
};
axios.request(propertyOptions).then(function (response) {
console.log(response.data);
i++;
if (propertyList.length < i) next();
});
}
next();
}发布于 2021-11-04 20:25:43
最直接的方法是在每次调用后短暂暂停。您可以通过使函数异步,并使用await将axios.request()赋值给变量(而不是随后使用.then()语法)来实现这一点。将睡眠计时器设置为保持在API限制内所需的任何值。
下面是我重构它的方法:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function buildCompleteProperties(){
for(let property of propertyList){
propertyOptions.params = {
zpid: property.zpid
}
try {
let { data } = await axios.request(propertyOptions);
console.log(data)
await sleep(1000)
} catch (error){
console.error(error);
}
}
}https://stackoverflow.com/questions/69845205
复制相似问题