Javascript 如果出现错误,请重试

Javascript 如果出现错误,请重试,javascript,node.js,function,Javascript,Node.js,Function,若函数返回错误,则不再执行其他代码。我需要重试此功能,直到成功。我怎么做 ... // API request... function(error, something) { if (!error) { something = true; // Etc... } else { // Code to try again. } } 试试这个 do { // do your stuff here }while(erro

若函数返回错误,则不再执行其他代码。我需要重试此功能,直到成功。我怎么做

... // API request...

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

  do {
    // do your stuff here
  }while(error)
对于旅游案例,您可以这样做:

function(error, something) {
    do {
        // do your stuff here
      }while(error)
}
做你想做的事直到错误变成错误

或者你可以在

    function(error, something) {
        if(!error){
            // this code is executed once
         }
            while(error){
                // do your stuff here
              }
        }
它将在第一次执行之前测试错误

例如

对于最后一条评论,您可以这样做(无循环):

试试这个

  do {
    // do your stuff here
  }while(error)
对于旅游案例,您可以这样做:

function(error, something) {
    do {
        // do your stuff here
      }while(error)
}
做你想做的事直到错误变成错误

或者你可以在

    function(error, something) {
        if(!error){
            // this code is executed once
         }
            while(error){
                // do your stuff here
              }
        }
它将在第一次执行之前测试错误

例如

对于最后一条评论,您可以这样做(无循环):


我更喜欢有一个称为self的函数,这样你就有了更多的自由

function repeat() {
  repeat()
}
然后你可以做各种各样的事情。你的例子是

const repeat = () => {
    // Your code
    if(error) {
        repeat()
    }
}
如果只运行一次,则创建一个自执行函数

(function repeat() {
    // Your code
    if(error) {
        repeat()
    }
})()
因为我们使用一个调用self的函数,所以我们可以使用setTimeout

(function repeat() {
    // Your code
    if(error) {
        setTimeout(() => {
            repeat()
        }, 100)
    }
})()

这使得代码有可能稍微中断,而不是运行none-stop。

我更喜欢有一个函数调用它自己,这样你就有了更多的自由

function repeat() {
  repeat()
}
然后你可以做各种各样的事情。你的例子是

const repeat = () => {
    // Your code
    if(error) {
        repeat()
    }
}
如果只运行一次,则创建一个自执行函数

(function repeat() {
    // Your code
    if(error) {
        repeat()
    }
})()
因为我们使用一个调用self的函数,所以我们可以使用setTimeout

(function repeat() {
    // Your code
    if(error) {
        setTimeout(() => {
            repeat()
        }, 100)
    }
})()

这使得代码有可能稍微中断,而不是运行none stop。

对不起,我不明白。你能解释一下吗?如果错误为false,它将执行do{}直到成功?这将始终至少执行一次代码,否则你可以使用while()循环我将它添加到答案中看看我不想在这里使用“//做你的事”,直到错误为false。那么我应该使用什么呢?在你的问题中,你说你想重试直到成功,所以我给你这个循环,它一直使用直到条件为真,否则你可以使用if条件,如果你不想循环对不起,我不明白。你能解释一下吗?如果错误为false,它将执行do{}直到成功?这将始终至少执行一次代码,否则你可以使用while()循环我将它添加到答案中看看我不想在这里使用“//做你的事”,直到错误为false。那么我应该使用什么呢?在你的问题中,你说你想重试直到成功,所以我给你这个循环,直到条件为真,否则如果你不想循环,你可以使用if条件