Dart超时等待未来

时间:2019-06-14 07:16:09

标签: asynchronous dart

如何使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();

1 个答案:

答案 0 :(得分:1)

调用Future.timeout时,您需要使用返回值来获取正确的行为。就您而言:

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