【问题标题】:Difference between .then() and .whenCompleted() methods when working with Futures?使用 Futures 时 .then() 和 .whenCompleted() 方法之间的区别?
【发布时间】:2019-03-27 15:43:01
【问题描述】:

我正在探索 Dart 中的 Futures,我对 Future 提供的这两种方法感到困惑,.then() 和 .whenCompleted()。它们之间的主要区别是什么?

假设我想使用 .readAsString() 读取 .txt,我会这样做:

void main(){
  File file = new File('text.txt');
  Future content = file.readAsString();
  content.then((data) {
    print(content);
  });  
}

所以.then() 就像一个回调,一旦 Future 完成就会触发一个函数。

但我看到还有 .whenComplete() 在 Future 完成后也可以触发一个函数。像这样:

void main(){
  File file = new File('text.txt');
  Future content = file.readAsString();
  content.whenComplete(() {
    print("Completed");
  });
}

我在这里看到的区别是.then() 可以访问返回的数据! .whenCompleted() 是做什么用的?我们什么时候应该选择一个而不是另一个?

【问题讨论】:

    标签: dart


    【解决方案1】:

    .whenComplete 将在 Future 完成并没有错误时触发一个函数,而 .then 将在 Future 完成且没有错误后触发一个函数。

    引用自 .whenComplete API 文档

    这是“finally”块的异步等价物。

    【讨论】:

    • 它们不是实际类型,而是generics。
    • 实际上不是......如果你把then放在catchError之后,then会被调用,因为catchError返回一个全新的Future,实际上如果要在catchError中返回一个错误.then 不会被触发,在异步代码中你的代码会是这样的:gist.github.com/Hexer10/87a6f38616f74321c85f2f91a5450d4e
    【解决方案2】:

    即使出现错误,then 仍然可以调用,前提是您指定了catchError。

    someFuture.catchError(
      (onError) {
        print("called when there is an error catches error");
      },
    ).then((value) {
      print("called with value = null");
    }).whenComplete(() {
      print("called when future completes");
    });
    

    所以,如果出现错误,上述所有回调都会被调用。

    【讨论】:

      【解决方案3】:

      .whenComplete = 当未来完成时调用.whenComplete 中的函数,无论它是通过值还是错误完成。

      .then = 返回一个新的 Future,它通过调用 onValue(如果这个 future 完成一个值)或 onError(如果这个 future 完成一个错误)的结果完成

      阅读 API DOC 的详细信息

      whenCompletethen

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-29
        • 2012-12-24
        • 1970-01-01
        • 2017-05-09
        • 1970-01-01
        • 1970-01-01
        • 2021-07-15
        • 1970-01-01
        相关资源
        最近更新 更多