简体   繁体   English

如何使用 NodeJS 以间隔发出 API 请求

[英]How to make API requests with intervals with NodeJS

sorry if this question has already been asked, I searched for it but couldn't find anything clear.抱歉,如果这个问题已经被问过,我搜索了它,但找不到任何清楚的东西。

How can I make API requests with intervals with NodeJS, for example, one request every 20 seconds?如何使用 NodeJS 以间隔发出 API 请求,例如每 20 秒一个请求?

This so I can respect the API limits, if I make all the requests at once, it'd crash.这样我就可以尊重 API 限制,如果我一次发出所有请求,它会崩溃。

Not sure if it matters, but I'm using Axios for the requests.不确定这是否重要,但我正在使用 Axios 来处理请求。

Please tell me if any other information is needed.请告诉我是否需要任何其他信息。 Thank you!谢谢!

It should be easy enough to to this with setInterval , the interval is specified in milliseconds.使用setInterval应该很容易做到这一点,间隔以毫秒为单位。

If you need more control over when the api is called, eg using a cron expression to schedule calls, I'd suggest trying node-cron .如果您需要更多地控制何时调用 api,例如使用 cron 表达式来安排调用,我建议尝试node-cron

const axios = require("axios");

async function callApi() {
    let response = await axios( { url: "https://jsonplaceholder.typicode.com/users" });
    console.log("Response:", response.data);
} 

function callApiEveryNSeconds(n) {
    setInterval(callApi, n * 1000);
}

callApiEveryNSeconds(20);

This was the best solution to my case:这是我的情况的最佳解决方案:

    let i = 0;
    let idInterval = setInterval(() => {
      if (i < dataFortheAPI.length) {
        funtionThatMakestheApiRequest(dataFortheAPI[i]);
        i++;
      } else {
        clearInterval(idInterval);
      }
    }, 22000);

You can use https://www.npmjs.com/package/request for the API request and setInterval().您可以将https://www.npmjs.com/package/request用于 API 请求和 setInterval()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM