【问题标题】:Async patterns in flutter/dart: Any downsides to async/await vs. raw Future API?Flutter/dart 中的异步模式:async/await 与原始 Future API 有什么缺点吗?
【发布时间】:2019-10-18 05:39:09
【问题描述】:

在 Flutter/Dart 应用程序中处理 Futures 的最佳方法是什么。处理原始的 Future api,还是使用带有 await 的异步函数?有什么优点/缺点还是完全取决于个人喜好?

由于生成的 javascript 代码的复杂性,似乎 async/await 的 AngularDart Project has tried to get rid。这显然不是 Flutter 应用程序关心的问题。但有时我认为 Future api 的表现力(和恕我直言的功能风格)比处理异步函数更有优势。

是否有任何技术原因可以避免使用 async/await 糖以支持直接处理 Future api? (我也尝试从flutter-dev mailing list without success 获得一些反馈)。

【问题讨论】:

  • 检查here:Why would you use the Future API instead of async and await?
  • @pskink 因为我大部分时间都喜欢函数式风格。例如,在编写像Future<Result> findResult() => compute().then((result) => result.doSomething()).then((result2) => result2.doSomethingElse())) 这样的小函数时,似乎比await (await ((await compute()).doSomething())).doSomethingElse() 更好

标签: flutter dart async-await


【解决方案1】:

Future 类 (https://api.dartlang.org/stable/2.3.1/dart-async/Future-class.html) 支持 anywait,这在 await 的顺序特性下是不可能复制的。但对于 80% 的用例,await 可能就足够了。

【讨论】:

  • Async/await 是我们在 Effective Dart 中推荐的内容
  • 是的,async/await 读起来更简洁,但我指出了它不够用的极少数情况。
【解决方案2】:

我认为没有任何技术原因可以避免 Async/await。除了您编写结果的方式之外,文档对它们的处理方式相同。这是个人喜好的事情。对我来说,如果您在一个序列中有多个期货,那么 Async/await 格式更容易遵循。

【讨论】:

    猜你喜欢
    • 2020-06-19
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 2021-05-26
    • 1970-01-01
    相关资源
    最近更新 更多