【问题标题】:Dart timeout on await Future等待未来飞镖超时
【发布时间】:2019-10-28 19:13:33
【问题描述】:

如何使await future 持续时间不超过 5 秒? 我需要它,因为在某些网络操作中,连接有时会产生静默错误。因此,我的客户只是等待几个小时而没有回应。相反,我希望它在客户端等待超过 5 秒时触发错误

我的代码可以触发错误但仍在等待

Future shouldnotlastmorethan5sec() async {
  Future foo = Future.delayed(const Duration(seconds: 10));;
  foo.timeout(Duration(seconds: 5), onTimeout: (){
    //cancel future ??
    throw ('Timeout');
  });
  await foo;
}
Future test() async {
  try{
    await shouldnotlastmorethan5sec(); //this shoud not last more than 5 seconds
  }catch (e){
    print ('the error is ${e.toString()}');
  }
}
test();

【问题讨论】:

    标签: asynchronous dart


    【解决方案1】:

    当您调用Future.timeout 时,您需要使用返回值来获得正确的行为。在你的情况下:

    Future shouldnotlastmorethan5sec() {
      Future foo = Future.delayed(const Duration(seconds: 10));
      return foo.timeout(Duration(seconds: 5), onTimeout: (){
        //cancel future ??
        throw ('Timeout');
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 2021-09-15
      • 2021-03-11
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      • 2019-05-30
      相关资源
      最近更新 更多