nodejs等待循环完成(异步 /等待 / promisse)
我正在尝试使一个循环在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以做类似的事情:
或者,我更喜欢使用
settimeout()
的承诺版本。 i最新版本的nodejs,您可以使用timerspromises.setTimeout()
,然后返回承诺:或者,,使用 带有
等待
>等待> :You can do something like this:
Or, I prefer using a promise version of
setTimeout()
. I the latest version of nodejs, you can usetimersPromises.setTimeout()
and it returns a promise:Or, use a
while
loop withawait
:使用递归:
您可以添加参数以自定义此函数/通过值,但这就是想法。
Use recursion:
You can add the parameters to customize this function/pass values in but this is the idea.
您可以通过导入基于承诺的
settimeout
来实现这一目标,该使用nodejs 16+运行,并以下如下:导入: import:
use: use:use:
You can achieve this by importing the promise based
setTimeout
that ships with NodeJs 16+ and using it as follows:Import:
Use:
为什么不尝试使用 promise.all 或
promise.allsettled
?因此,您可以使用并发立即获取所有数据,而是一个一个一个。如果您需要一个一个一个,我建议您使用Why don't you try to use
Promise.all
orPromise.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 usefor-await...of
.