【发布时间】:2023-02-07 17:18:40
【问题描述】:
在我的代码中,“getResponse”只执行一次。我该如何解决? 我不想将“getResponse”放在“重试”中。
import "dart:math";
Future getResponse(int sec) async {
return Future.delayed(Duration(seconds: sec), () {
int rand = Random().nextInt(10);
print(rand);
if (rand < 5) {
return "success";
} else {
throw "rejected";
}
});
}
Future retry(Future f, [int count = 0]) async {
try {
return (await f);
} catch (e) {
if (count < 5) {
print(e);
retry(f, count + 1); // I think here is wrong.
}
}
}
void main() async => await retry(getResponse(1));
函数“重试”应该执行 getResponse 直到它成功
【问题讨论】:
-
它在异常时被调用 5 次
-
只需在循环中调用
getResponse方法