Reputation: 20406
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();
Upvotes: 5
Views: 3744
Reputation: 76183
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');
});
}
Upvotes: 5