Arnas A. Arnas A. - 3 months ago 12
Javascript Question

JS try again if error

if function returns error, further code is no longer executing. I need to retry this function until success. How can I do it?

... // API request...

function(error, something) {
if (!error) {
something = true;
// Etc...
}
else {
// Code to try again.
}
}

Answer

Try this

  do {
    // do your stuff here
  }while(error)

For tour case you can do it like this :

function(error, something) {
    do {
        // do your stuff here
      }while(error)
}

To do what you want until the error become false

Or you can use while

    function(error, something) {
        if(!error){
            // this code is executed once
         }
            while(error){
                // do your stuff here
              }
        }

It will test the error before executing the first time

For more example take a look here

For the last comment you can do it like this (without loop) :

function Test(error, something) {
        if(!error){
            // your code that you want to execute it once
        }
        else {
            // do stuff
            Test(error, something); // re-call the function to test the if
        }
    }
Comments