簡體   English   中英

使用 fetch 在節點中進行異步 api 調用的最佳實踐?

[英]Best practice for making async api calls in node using fetch?

我正在 nodeJS、express & mysql 中構建一個應用程序,我正在使用節點提取從幾個不同的 API:s 收集數據,其中一個限制為每 5 分鍾調用 200 次。 為了完全更新我的數據庫,我基本上需要不間斷地運行對此 API 的調用,目前我正試圖通過在 for 循環/foreach 中使用睡眠來保持在限制范圍內。

問題是每個請求的時間可能會有所不同,看起來我可以使調用更有效,而不是不斷地為每個請求休眠相同的時間。 我想知道是否有更好的方法來做到這一點? 我一直在考慮讓 199 調用異步,然后正好等待 5 分鍾,然后重復它......但我不知道如何。

找不到關於此的主題,但如果已經有一個好的答案,請鏈接一個。 非常感謝您的回答,如果您有其他反饋,請告訴我!

  for (let i = 1; i < length; i++) {
    try {
      let id = IdCollection[i];
      let resultFromApiCall = await datafetcher.MakeApiCall(id);

      await sleep(2000);

    } catch (error) {
      console.log("Error in api-calls" + error);
    }
  }```

我認為這是一個品味問題。

我會立即發出所有允許的請求,然后等到 5 分鍾的間隔結束。

  // constants to define the restrictions
  const restrictionCalls = 5;
  const restrictionTime = 300000; // 5 * 60 * 1000

  let throttleTimer = Date.now(); // when did we start this interval?
  let throttleCounter = 0; // how many calls did we make in this interval?

  for (let i = 1; i < length; i++) {
    try {
      let id = IdCollection[i];
      throttleCounter++;
      let resultFromApiCall = await datafetcher.MakeApiCall(id);
    } catch (error) {
      console.log("Error in api-calls" + error);
    }

    if(throttleCounter === restrictionCalls) {
      const timePassed = Date.now() - throttleTimer;
      const waitTime = restrictionTime - timePassed;
      if(waitTime > 0) await sleep(waitTime);

      // reset
      throttleTimer = Date.now();
      throttleCounter = 0;
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM