将Future.then()替换为async/await

3

我一直认为async/await比Futures API更加优雅和性感,但现在我面临这样一种情况:Future API的实现非常简短和简洁,而async/await的替代方案似乎冗长且丑陋。

我在注释中标记了我的两个问题#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会增加多少开销?我应该将已解决的future作为实例变量,也就是说

completedFuture ??= await item_int2string;
return completedFuture[id];
2个回答

3

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

对于第二点,不用担心异步代码的性能影响。代码将以与同步代码相同的速度执行,只是稍后在回调发生时执行。异步存在的唯一原因是为了方便让代码在系统等待异步调用部分返回时继续运行。例如,在等待磁盘加载文件时不会阻塞用户界面。

我建议您阅读Dart中有关异步的基本文档


1

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接