微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 Axios 顺序获取远程文档/对象数组?

如何解决如何使用 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(连同forfor..infor await..ofwhiledo..wile)是一个句法循环,而数组迭代器方法接受回调。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?