[英]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.
}
}
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 因为我们使用了一个自我调用的函数,所以可以使用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. 这使得代码可以在不停止运行的情况下稍作休息。
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.