飞镖超时等待未来

TSR*_*TSR 5 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();
Run Code Online (Sandbox Code Playgroud)

Ale*_*uin 5

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

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