【发布时间】: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