1

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. So I want the while loop to keep calling getStatus() to get the value of STATUS and break the loop when it is SUCCEEDED. I also want to put a delay between each iteration.

This can't be done easily with Nodejs. So please help me out.

1
  • Restructure using a promise and setTimeout()-based retries? Commented Sep 23, 2017 at 1:21

2 Answers 2

2

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.

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
Sign up to request clarification or add additional context in comments.

2 Comments

for some reason this code only runs once when I test
this would implicate that the getStatus() function returned "SUCCEEDED" after the second time. You can fake getStatus and see when no "SUCCEEDED" is ever returned the setInterval callback will be called consequently
0

You can use setInterval to continually do something on a delay. 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.

Once a call is successful you can clear the interval.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.