Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 209 Vote(s) - 3.53 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Await future for a specific time

#1
How would you wait for future response for a specific amount of time?

Say, we make a http post request and await for its response before we close the http request, but, we wait for only 3 secs, else we close the request.

How would you achieve that?

Something like

Future makePostReq() async{
....

await http response for 3 secs

....

if(response) {
... Do something with it
}

Http.close

}
Reply

#2
### Future.any([*asyncfunc*, ...])

Here's an example of using Remi's `Future.any` solution where the future that returns first, will be used. The other is discarded.

So, the first future is your data-gathering/slow function and the other is a fallback when your call is taking too long.
```
dynamic result = await Future.any([
getData(fakeDelay: seconds), // ← hope this returns first
timeoutAfter(sec: timeout, onTimeout: () => 'Timed Out!', ) // ← waited too long, do this
]);
```


### Example in Flutter Page

Here's a copy/paste example for a Flutter page:

(look at your debug/run output window for messages)
```
import 'package:flutter/material.dart';

class FutureTimeoutPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Future or Timeout Page'),
),
body: FutureAnyExample(),
);
}
}

class FutureAnyExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Complete before timeout or timeout:'),
SizedBox(height: 30,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(onPressed: () => getDataOrTimeout(seconds: 1, timeout: 3),
child: Text('In Time')),
ElevatedButton(onPressed: () => getDataOrTimeout(seconds: 5, timeout: 3),
child: Text('Too Slow'))
],
)
],
);
}

Future<void> getDataOrTimeout({int seconds, int timeout}) async {
/// In Future.any, put as many async functions as you need.
/// Whichever completes first, will be returned. All others are discarded
dynamic result = await Future.any([
getData(fakeDelay: seconds), // ← hope this returns first
timeoutAfter(sec: timeout, onTimeout: () => 'Timed Out!', ) // ← waited too long, do this
]);

print(result);
}

/// Mock of a long-running operation like getting DB data, or API call
Future<String> getData({int fakeDelay}) async {
return Future.delayed(Duration(seconds: fakeDelay), () => 'Data returned!');
}

/// Do this in case my long-running op takes too long
/// Can run a function or just return some message
Future<dynamic> timeoutAfter({int sec, Function() onTimeout}) async {
return Future.delayed(Duration(seconds: sec), onTimeout);
}
}
```
Reply

#3
You can do it very easily

try {
var response = await Http.get("YourUrl").timeout(const Duration(seconds: 3));
if(response.statusCode == 200){
print("Success");
}else{
print("Something wrong");
}
} on TimeoutException catch (e) {
print('Timeout');
} on Error catch (e) {
print('Error: $e');
}
This example sets timeout to 3 second. If it has been 3 seconds and no response received, it will throw `TimeoutException`

Import this :

import 'package:http/http.dart' as Http;
import 'dart:async';

Reply

#4
You can use `Future.any` constructor to make a race condition

final result = await Future.any([
Future.value(42),
Future.delayed(const Duration(seconds: 3))
]);


You can also use [`Future.timeout`](

[To see links please register here]

) method


final result = await Future.value(42).timeout(const Duration(seconds: 3));
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through