nodejs等待循环完成(异步 /等待 / promisse)

发布于 2025-02-04 11:24:38 字数 650 浏览 2 评论 0原文

我正在尝试使一个循环在API中获取一些信息,首先我需要此循环等待请求完成并在继续下一个阵列值之后,然后在循环完成后,然后我需要它来调用该功能再次每5秒,但仅在上一个通话结束后。

这样的事情:

let ids = [1, 2];

async function getInfoAPI(ids) {

   for (const id of ids){
      const apiInfo = await fetch(`https://apiurl/${id}`);
      const infoJSON = await apiInfo.json();

      //Do more things here
   }
}

现在我需要调用功能并等待循环完成。循环完成后,请等待5秒钟,然后再次调用getInfofromapi函数。我尝试了setInterval,但是如果由于某种原因循环需要超过5秒钟的响应,则即使没有完成上一个循环,getInfofromapi即使它没有完成。

setInterval(function(){ 
        getInfoAPI(ids);
}, 5000);

有什么办法可以使用诺言或类似的东西来做到这一点?

I'm trying to make a loop fetching some info in an API, first I need this loop for to wait for the request to finish and after continue for the next array value, after the loop finish, then I need it to call that function again every 5 seconds, but only after the previous call ends.

Something like this:

let ids = [1, 2];

async function getInfoAPI(ids) {

   for (const id of ids){
      const apiInfo = await fetch(`https://apiurl/${id}`);
      const infoJSON = await apiInfo.json();

      //Do more things here
   }
}

Now I need to call the function and wait for the loop to finish. After the loop is completed then wait for 5 seconds and call the getInfoFromAPI function again. I tried setInterval but if the loop, for some reason, takes more than 5 seconds to respond, the getInfoFromAPI will be called again even if it didn't finish the previous loop.

setInterval(function(){ 
        getInfoAPI(ids);
}, 5000);

Is there any way I could do that using promises or something like that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一人独醉 2025-02-11 11:24:38

您可以做类似的事情:

function run() {
    getInfo(...).then(() => {
        setTimeout(run, 5000)
    });
}

run().catch(err => {
   console.log(err);
});

或者,我更喜欢使用settimeout()的承诺版本。 i最新版本的nodejs,您可以使用timerspromises.setTimeout(),然后返回承诺:

import { setTimeout } from 'timers/promises';

async function run() {
    await getInfo(...)
    await setTimeout(5000);
    return run();
}

run().catch(err => {
   console.log(err);
});

或者,,使用 带有等待>等待> :

import { setTimeout } from 'timers/promises';

async function run() {
    while (true) {
        await getInfo(...)
        await setTimeout(5000);
    }
}

run().catch(err => {
   console.log(err);
});

You can do something like this:

function run() {
    getInfo(...).then(() => {
        setTimeout(run, 5000)
    });
}

run().catch(err => {
   console.log(err);
});

Or, I prefer using a promise version of setTimeout(). I the latest version of nodejs, you can use timersPromises.setTimeout() and it returns a promise:

import { setTimeout } from 'timers/promises';

async function run() {
    await getInfo(...)
    await setTimeout(5000);
    return run();
}

run().catch(err => {
   console.log(err);
});

Or, use a while loop with await:

import { setTimeout } from 'timers/promises';

async function run() {
    while (true) {
        await getInfo(...)
        await setTimeout(5000);
    }
}

run().catch(err => {
   console.log(err);
});
深居我梦 2025-02-11 11:24:38

使用递归:

async function getInfoPeriodically() {
  await getInfoAPI(ids);
  setTimeout(() => {
    getInfoPeriodically()
  }, 5000);
}

您可以添加参数以自定义此函数/通过值,但这就是想法。

Use recursion:

async function getInfoPeriodically() {
  await getInfoAPI(ids);
  setTimeout(() => {
    getInfoPeriodically()
  }, 5000);
}

You can add the parameters to customize this function/pass values in but this is the idea.

初与友歌 2025-02-11 11:24:38

您可以通过导入基于承诺的settimeout来实现这一目标,该使用nodejs 16+运行,并以下如下:

导入: import:

import { setTimeout } from "timers/promises"

use: use:use:

while (true) {
  await getInfoAPI(ids);
  await setTimeout(5000);
}

You can achieve this by importing the promise based setTimeout that ships with NodeJs 16+ and using it as follows:

Import:

import { setTimeout } from "timers/promises"

Use:

while (true) {
  await getInfoAPI(ids);
  await setTimeout(5000);
}
Saygoodbye 2025-02-11 11:24:38

为什么不尝试使用 promise.all promise.allsettled ?因此,您可以使用并发立即获取所有数据,而是一个一个一个。如果您需要一个一个一个,我建议您使用

Why don't you try to use Promise.all or Promise.allSettled? With that you can use concurrency to fetch all the data at once, instead that one by one. In case you need to do it one by one, I suggest you to use for-await...of.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文