首页 > 解决方案 > 如何按顺序使用 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]

标签: javascriptecmascript-6axios

解决方案


您可以简单地使用一个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)是一个语法循环,而数组迭代器方法需要回调。


推荐阅读