我正在使用 axios 向 Deezer API 发出请求。不幸的是,使用 Deezer 的 API,当您请求艺术家的专辑时,它不包括专辑曲目。因此,我正在通过请求艺术家的专辑,然后对每个专辑执行后续的 axios 请求来解决这个问题。我遇到的问题是 API 将请求限制为每 5 秒 50 个。如果一位艺术家拥有超过 50 张专辑,我通常会收到“超出配额”错误。有没有办法将 axios 请求限制为每 5 秒 50 个,特别是在使用 axios.all 时?
var axios = require('axios');
function getAlbums(artistID) {
axios.get(`https://api.deezer.com/artist/${artistID}/albums`)
.then((albums) => {
const urls = albums.data.data.map((album) => {
return axios.get(`https://api.deezer.com/album/${album.id}`)
.then(albumInfo => albumInfo.data);
});
axios.all(urls)
.then((allAlbums) => {
console.log(allAlbums);
});
}).catch((err) => {
console.log(err);
});
}
getAlbums(413);
首先,让我们看看你是什么really需要。如果您有大量相册,您的目标是最多每 100 毫秒发出一次请求。 (使用axios.all
对于这个问题与使用没有什么不同Promise.all
,您只想等待所有请求完成。)
现在,有了 axios,您就拥有了拦截 API,允许在请求之前插入您的逻辑。所以你可以使用这样的拦截器:
function scheduleRequests(axiosInstance, intervalMs) {
let lastInvocationTime = undefined;
const scheduler = (config) => {
const now = Date.now();
if (lastInvocationTime) {
lastInvocationTime += intervalMs;
const waitPeriodForThisRequest = lastInvocationTime - now;
if (waitPeriodForThisRequest > 0) {
return new Promise((resolve) => {
setTimeout(
() => resolve(config),
waitPeriodForThisRequest);
});
}
}
lastInvocationTime = now;
return config;
}
axiosInstance.interceptors.request.use(scheduler);
}
它的作用是对请求进行计时,以便它们在intervalMs
毫秒间隔。
在你的代码中:
function getAlbums(artistID) {
const deezerService = axios.create({ baseURL: 'https://api.deezer.com' });
scheduleRequests(deezerService, 100);
deezerService.get(`/artist/${artistID}/albums`)
.then((albums) => {
const urlRequests = albums.data.data.map(
(album) => deezerService
.get(`/album/${album.id}`)
.then(albumInfo => albumInfo.data));
//you need to 'return' here, otherwise any error in album
// requests will not propagate to the final 'catch':
return axios.all(urls).then(console.log);
})
.catch(console.log);
}
然而,这是一种简单化的方法,在您的情况下,您可能希望在请求数量少于 50 的情况下尽快收到结果。为此,您必须在调度程序中添加某种计数器来计数请求数量并根据间隔和计数器延迟其执行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)