Dart timeout on await Future

ぃ、小莉子 提交于 2020-12-29 13:17:14

问题


How to make a await future not last more than 5 seconds ? I need it because in some networking operation, the connection is sometimes producing silent error. Hence my client just wait for hours with no response. Instead, I want it trigger an error when the clients waits for more than 5 seconds

My code can trigger the error but it is still waiting

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:


When you call Future.timeout you need to use the return value to get the correct behaviour. In your case:

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


来源:https://stackoverflow.com/questions/56593256/dart-timeout-on-await-future

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!