code-8
code-8

Reputation: 58810

Create a while loop that break after a certain tries - NodeJS

Description

I'm trying to write a while loop to my monitor API. The goal is to call the API until the percent is reaching 100. I want to call it every 5 seconds. Usually in 30 seconds, the percent will reach 100%. I want to throw the error after 10 tries which is equal to 50 seconds.


I've tried

let monitor = await Service.monitor(session,taskId);
let percent = JSON.parse(monitor).result[0].data.percent;

let tryCount = 0;
let tryMax = 10;
while (percent < 100 || tryCount < tryMax) {
    setTimeout(function() {
        let percent = JSON.parse(monitor).result[0].data.percent;
        tryCount++;
    }, 5000);

    console.log('in a while loop ',tryCount, percent);

    if(tryCount == 10){
        var err = new Error('Error')
        throw err
    }
}

Result

I got so many

in a while loop  0 0
in a while loop  0 0
...
in a while loop  0 0
in a while loop  0 0

Question

Why my tryCount keep showing as 0 and not increment?

How would one create a while-loop that does something like that ?

Upvotes: 0

Views: 292

Answers (1)

dGRAMOP
dGRAMOP

Reputation: 793

You need to refresh the monitor variable, instead of just re-parsing. You had the right idea, just had to take it further

Also, I moved you to a setInterval from a while loop, that way you can run things on an automatically timed loop, the "correct" way to do it

let monitor = await Service.monitor(session,taskId);
let percent = JSON.parse(monitor).result[0].data.percent;

let tryCount = 0;
let tryMax = 10;
setInterval(function(){(percent < 100 || tryCount < tryMax) {
    if(percent < 100 || tryCount < tryMax){
    monitor = await Service.monitor(session,taskId);
    let percent = JSON.parse(monitor).result[0].data.percent;
    tryCount++;
    console.log('in a while loop ',tryCount, percent);

    if(tryCount == 10){
        var err = new Error('Error')
        throw err
    }
    }else{
    clearInterval(this);
    }
},5000)

And I'm assuming you're somehow reloading monitor, because even if you re-parse it, if it's a connection on a different server, you'll need to reload that.

Upvotes: 3

Related Questions