Reputation: 61
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.
}
}
Upvotes: 2
Views: 10498
Reputation: 730
I prefer having a function calling it self so you have more freedom
function repeat() {
repeat()
}
Then you can all kind of tings. Your example would be
const repeat = () => {
// Your code
if(error) {
repeat()
}
}
If you only run it once, then make a self executing function.
(function repeat() {
// Your code
if(error) {
repeat()
}
})()
Because we use a function calling it self we can use setTimeout
(function repeat() {
// Your code
if(error) {
setTimeout(() => {
repeat()
}, 100)
}
})()
This makes it possible for the code to have a little break insted of running none stop.
Upvotes: 6
Reputation: 419
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
}
}
Upvotes: 3