如何解决如何使用 Axios 顺序获取远程文档/对象数组?
我有一组文档/行/对象 ID(yelp 业务),我想使用 axios 一个一个地获取它们的关联数据。我使用以下代码段来获取它们,但我得到的都是 axios 错误,代码为 429(请求过多)[Unhandled promise rejection: Error: Request Failed with status code 429]
。我使用了以下代码的多种形式,但结果相同:
export const _fetchBusinessesDetails = async (ids : any[]) => {
const businesses : Array<string> = [];
const headers = {
Authorization: 'Bearer <token>','Content-Type': 'application/json',};
ids.map(async (id : string) => {
const res = await axios.get(`https://api.yelp.com/v3/businesses/${id}`,{ headers });
console.log(res.data || res.response.data.message);
if (res.data) {
businesses.push(res.data);
} console.log(res.response.data.message);
});
return businesses;
};
错误代码:[Unhandled promise rejection: Error: Request Failed with status code 429]
解决方法
您可以简单地使用 for..of
循环,并在其中使用 await
:
export const _fetchBusinessesDetails = async (ids : string[]) => {
const businesses : Array<string> = [];
const headers = {
Authorization: 'Bearer <token>','Content-Type': 'application/json',};
for(const id of ids) {
const res = await axios.get(`https://api.yelp.com/v3/businesses/${id}`,{ headers });
console.log(res.data || res.response.data.message);
if (res.data) {
businesses.push(res.data);
}
console.log(res.response.data.message);
};
return businesses;
};
区别在于for..of
(连同for
、for..in
、for await..of
、while
、do..wile
)是一个句法循环,而数组迭代器方法接受回调。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。