【问题标题】:Replace Future.then() with async/await用 async/await 替换 Future.then()
【发布时间】: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


    【解决方案1】:

    thenawait 是不同的。 await 将在那里停止程序,直到 Future 任务完成。但是then 不会阻止该程序。 then 中的块会在之后Future 任务完成时执行。

    如果您希望程序等待Future 任务,请使用await。如果您希望您的程序继续运行并且Future 任务在“后台”执行它,请使用then

    【讨论】:

      【解决方案2】:

      1: 我如何在这里使用 async/await 而不是 Future.then()?最优雅的解决方案是什么?

      异步方法具有传染性。这意味着您的 ItemsRepository 方法必须是异步的才能在内部使用 await。这也意味着您必须从其他地方异步调用它。见例子:

      Future<dynamic> ItemsRepository() async {
          // #1
          myString = await rootBundle.loadString('assets/data/item_int2string.json');
          // do something with my string here, which is not in a Future anymore...
        }
      

      请注意,使用 .then 与异步函数中的 await 完全一样。它只是语法糖。请注意,您将使用 .then 与您的示例不同:

        ItemsRepository() {
          // #1
          
           rootBundle.loadString('assets/data/item_int2string.json').then((String myString) {
             // do something with myString here, which is not in a Future anymore...
           });
        }
      

      对于#2,不要担心异步代码对性能的影响。代码将以与同步代码相同的速度执行,只是稍后发生回调时。 async 存在的唯一原因是有一种简单的方法允许代码在系统等待异步调用部分的返回时继续运行。例如,在等待磁盘加载文件时不要阻塞 UI。

      我建议你阅读basic docs about async in Dart

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-19
        • 2020-02-05
        • 1970-01-01
        • 2014-02-16
        • 1970-01-01
        相关资源
        最近更新 更多