【发布时间】:2019-06-12 08:16:02
【问题描述】:
我一直认为 async/await 比 Futures API 更优雅/更性感,但现在我面临的情况是 Future API 实现非常短而简洁,而 async/await 替代方案似乎冗长而丑陋。
我在 cmets 中标记了我的两个问题 #1 和 #2:
class ItemsRepository
{
Future<dynamic> item_int2string;
ItemsRepository() {
// #1
item_int2string =
rootBundle.loadString('assets/data/item_int2string.json').then(jsonDecode);
}
Future<String> getItem(String id) async {
// #2
return await item_int2string[id];
}
}
#1:我如何在这里使用 async/await 而不是 Future.then()?最优雅的解决方案是什么?
#2:如果方法被大量调用,这是否有效? await 增加了多少开销?我是否应该将已解决的未来设为实例变量,也就是
completedFuture ??= await item_int2string;
return completedFuture[id];
【问题讨论】:
标签: dart async-await flutter