如果出错,JS 再试一次

Arn*_* A. 1 javascript function node.js

如果函数返回错误,则不再执行进一步的代码。我需要重试这个功能直到成功。我该怎么做?

... // API request...

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

J. *_*Eng 5

我更喜欢有一个函数调用它自己,所以你有更多的自由

function repeat() {
  repeat()
}
Run Code Online (Sandbox Code Playgroud)

然后你可以进行各种调整。你的例子是

const repeat = () => {
    // Your code
    if(error) {
        repeat()
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你只运行一次,那么做一个自执行函数。

(function repeat() {
    // Your code
    if(error) {
        repeat()
    }
})()
Run Code Online (Sandbox Code Playgroud)

因为我们使用一个自调用函数,所以我们可以使用 setTimeout

(function repeat() {
    // Your code
    if(error) {
        setTimeout(() => {
            repeat()
        }, 100)
    }
})()
Run Code Online (Sandbox Code Playgroud)

这使得代码有可能在不停地运行时有一点中断。