简体   繁体   中英

Dart async/await encapsulation

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM