简体   繁体   English

如何在Node.js中创建带有延迟的While循环

[英]How to create a while loop with delay in nodejs

Let's say I have this pseudo code: 假设我有这个伪代码:

var STATUS = '';
while (STATUS !== "SUCCEEDED") {
    STATUS = getStatus();
    anotherFunc();
    delay(3s);
}

The goal of this code is to keep calling an api to check a status of something, the api returns IN_PROGRESS or SUCCEEDED. 此代码的目标是继续调用api来检查某物的状态,该api返回IN_PROGRESS或SUCCEEDED。 So I want the while loop to keep calling getStatus() to get the value of STATUS and break the loop when it is SUCCEEDED. 因此,我希望while循环继续调用getStatus()以获取STATUS的值,并在成功时中断循环。 I also want to put a delay between each iteration. 我还想在每次迭代之间设置一个延迟。

This can't be done easily with Nodejs. 使用Nodejs很难做到这一点。 So please help me out. 所以请帮帮我。

you don't even need a while loop for that, simply use setInterval() and within the callback check if your condition is satisfied to clear the created interval. 您甚至不需要while循环,只需使用setInterval()并在回调中检查是否满足您的条件以清除创建的间隔。

var STATUS = '',
    idx = setInterval(function() {
        STATUS = getStatus();
        if (STATUS === "SUCCEEDED") { // I guess you wanted a check for STATUS instead of VAR
            return clearInterval(idx);
        }
        anotherFunc();
    }, 3000); // the interval when to call the function again 3000ms = 3sek

You can use setInterval to continually do something on a delay. 您可以使用setInterval连续延迟执行某些操作。 It accepts a function which you can use to do the api call, but before you do the call you should check if the last call was successful. 它接受一个可用于进行api调用的函数,但是在执行该调用之前,您应该检查上一次调用是否成功。

Once a call is successful you can clear the interval. 通话成功后,您可以清除间隔。

https://nodejs.org/api/timers.html#timers_setinterval_callback_delay_args https://nodejs.org/api/timers.html#timers_setinterval_callback_delay_args

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

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