在 fetch API 调用中设置延迟

问题描述 投票:0回答:3

我循环遍历 id 数组并每次使用 id 调用 API。
代码可以工作,但问题是每次循环中获得的结果不一致。在某些循环中,响应是“您已达到每秒最大速率限制”。
所以我在fetch函数中添加了3秒的延迟,但似乎不起作用。

代码:

export async function getThirdAPI(access_token, id_array, globalObject) {
  
 const apiPromises = id_array.map(async (id) => {
   return new Promise(resolve => setTimeout(resolve, 3000)).then(async()=>{
    let url = `${baseAPI}/participants/${id}`;
    var obj = {
      method: 'GET',
      headers: {  
      authorization: `Bearer ${access_token}`
         }
    }
    const response = await fetch(url, obj);
    return await response.json();
    })
  });

  const results = await Promise.all(apiPromises);
  console.log(results)

  globalObject.store_data.push(...results);

  return globalObject;
}

当我

console log
“结果”时,我得到如下所示的信息:

{
  page_count: 1,
  page_size: 300,
  total_records: 2,
  next_page_token: '',
  participants:[ Object }
},
{
  page_count: 1,
  page_size: 300,
  total_records: 3,
  next_page_token: '',
  participants:[ Object }
},
{
  code: 429,
  message: "You have reached the maximum per-second rate limit. Try again later"
},
{
  page_count: 1,
  page_size: 300,
  total_records: 11,
  next_page_token: '',
  participants:[ Object }
},
{
  code: 429,
  message: "You have reached the maximum per-second rate limit. Try again later"
}

任何建议都会很棒!

javascript timeout settimeout fetch-api
3个回答
2
投票

你可以安装这个 pckg npm install sleep-promise

import sleep from "sleep-promise";

   
function fetchUrl(url) {
  return fetch(url)
    .then(res => res.json())
    .then(sleep(2000));
}

0
投票

一个小技巧的解决方案是预先安排所有的承诺并增加延迟。第一个在 500 毫秒后,第二个在 1000 毫秒后,第三个在 1500 毫秒后等等

var delay = 1000;

const apiPromises = id_array.map(async(id, index) => {
  return new Promise(resolve => setTimeout(resolve, delay * index)).then(async() => {
    let url = `${baseAPI}/participants/${id}`;
    var obj = {
      method: 'GET',
      headers: {
        authorization: `Bearer ${access_token}`
      }
    }
    const response = await fetch(url, obj);
    return await response.json();
  })
});

0
投票

我对你的问题有什么建议。我最近以这种方式应用了一个干净的解决方案。所以你应用了随机延迟。

function RandomNumber(min, max, decimal) {
  const rand = Math.random() * (max - min) + min;
  const power = Math.pow(10, decimal);
  return Math.floor(rand * power) / power;
}

(function callApi(i) {
  setTimeout(function () {
    YOUR_API_CALL_PROCESS_HERE

    i++;
    if (i < id_array.length) {
      callApi(i);
    }
  }, RandomNumber(1000, 2000, 0));
})(0);
© www.soinside.com 2019 - 2024. All rights reserved.