javascript - 如何按顺序使用 Axios 获取远程文档/对象数组?
问题描述
我有一组文档/行/对象 ID(yelp 业务),我想使用 axios 一个一个地获取它们的关联数据。我使用以下代码片段来获取它们,但我得到的都是 axios 错误,代码为 429 (too many requests) [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
)是一个语法循环,而数组迭代器方法需要回调。
推荐阅读
- r - 如何将 mapply 与列表一起使用
- javascript - 删除/onDisconnect 在注销时不起作用
- django - Nginx 反向代理到 django 应用程序,图像样式未显示
- flutter - 在 API 调用期间使用 Flutter bloc 设置加载状态
- ruby-on-rails-6.1 - 错误数量的参数(给定 0,预期 1)rails 6.1.1
- kubernetes - Kubernetes Pod/容器网络
- php - 如何使用 cURL 下载 Facebook 图片?
- python - 是否可以获得 Dash-Cytoscape 图形工具提示?
- python - Python Selenium Chromedriver,无法检测到刷新
- reactjs - 执行多重依赖突变 - grandstack apollo graphql 3.3