hay我向 API 发出大量请求,我需要控制请求流
我有使用 axios 发出请求并返回承诺的功能,我执行数组并发出请求,然后我使用 Promise.all(( 完成请求,没有任何延迟和控制,我可以在其中放置一些控制函数来限制请求
,然后再将它们发送到 API我的得到功能:
return new Promise((resolve, reject) => {
console.log(`Getting address for ${lat}, ${lng}...`);
// Make sure we pass lat,lng to the API.
axios.get(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&result_type=locality&result_type=administrative_area_level_1&result_type=country&key=${apiKey}`)
.then(response => {
return resolve(response)
})
.catch(error => {
return reject(error.message)
}).catch(reject => {
return reject
})
})
}
然后我去真实数组并使用 get func
const newData = data.map(async item => {
let results = ''
let reqStatus = ''
if (item.Longitude !== "blank") {
const req = await getAddress(item.Longitude, item.Latitude).catch((error) => {
console.log(error);
});
reqStatus = req.status
results = req.data
} else {
results = 'blank'
}
let newItem = ''
//console.log(JSON.stringify(results, null, 2))
console.log(`status: ${reqStatus} ${results.status}`)
if (reqStatus == '200' && results.status == 'OK') {
const rstlength = results.results[0].address_components.length
newItem = {
...item,
//results_from_google: results, //results.results[0].address_components[0].long_name
address_1: rstlength > 0 ? results.results[0].address_components[0].long_name : 'blank',
address_2: rstlength > 1 ? results.results[0].address_components[1].long_name : 'blank',
address_3: rstlength > 2 ? results.results[0].address_components[2].long_name : 'blank',
address_4: rstlength - 1 > 3 ? results.results[0].address_components[3].long_name : 'blank'
}
} else {
newItem = {
...item,
//results_from_google: results, //results.results[0].address_components[0].long_name
address_1: 'blank',
address_2: 'blank',
address_3: 'blank',
address_4: 'blank'
}
}
return newItem;
})
现在如何延迟请求?
你可以试试:https://www.npmjs.com/package/bottleneck
const limiter = new Bottleneck({
minTime: 333
});
limiter.schedule(() => myFunction(arg1, arg2))
.then((result) => {
/* handle result */
});