我想返回小数部分,但是如果该函数花费太多时间,则该函数必须放弃。我试过了,但是没用...我可能做错了。你能告诉我我的错误吗?
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;
}
最佳答案
此代码有几个问题。
如果要返回异步操作的结果,则返回类型必须为Future<...>
Future<String> decimalToFractional(double d) async {
然后,您可以像这样消耗结果
main() async {
print(await decimalToFractional(123456789.123456789));
}
如果要使超时生效,则需要返回事件循环。只要同步执行正在运行,超时就不会触发。
另请参阅https://stackoverflow.com/a/22473556/217408
关于dart - Dart异步/等待封装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30186108/