【问题标题】:How to make new "Future" instance based on function parameter in Dart?如何根据 Dart 中的函数参数创建新的“Future”实例?
【发布时间】: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方法

标签: flutter dart dartpad


【解决方案1】:

你不能“重试”未来。一旦完成,就完成了。但是,您可以通过传递“未来工厂”(产生相关未来的功能)而不是未来来每次创建一个新工厂:

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";
    }
  });
}

// pass the factory function here
Future retry(Future Function() f, [int count = 0]) async {
  try {
    // call the function here to get a future to await
    return (await f());
  } catch (e) {
    if (count < 5) {
      print(e);
      retry(f, count + 1); 
    }
  }
}

// here, a function returning a future, instead of the future itself is passed
void main() async => await retry(() => getResponse(1));

建议使用循环而不是递归的评论可能也很准确。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 2020-09-03
    • 2019-12-17
    • 2017-11-05
    • 1970-01-01
    相关资源
    最近更新 更多