Reputation: 1329
I want to return fractional of a decimal, but if the function takes too much time, the function must give up. I tried this, but it doesn't work... I probably did something wrong. Could you to show me my mistake?
String decimalToFractional(double d) async {
var df = 1.0;
var top = 1;
var bot = 1;
var future = new Future<String>(() {
while (df != d) {
if (df < d) {
top += 1;
} else {
bot += 1;
top = (d * bot).toInt();
}
df = top / bot;
}
return new Future.value('$top/$bot');
});
future.timeout(new Duration(seconds: 2), onTimeout: () => new Future.value(d.toString()));
return await future;
}
Upvotes: 1
Views: 387
Reputation: 657148
There are several problems with this code.
If you want to return the result of an async operation the return type has to be Future<...>
Future<String> decimalToFractional(double d) async {
You can then consume the result like
main() async {
print(await decimalToFractional(123456789.123456789));
}
If you want timeout to take effect you need to return to the event loop. As long as sync execution is running timeout doesn't fire. See also https://stackoverflow.com/a/22473556/217408
Upvotes: 1