使用Futures时.then()和.whenCompleted()方法之间的区别? [英] Difference between .then() and .whenCompleted() methods when working with Futures?

查看:23
本文介绍了使用Futures时.then()和.whenCompleted()方法之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm exploring Futures in Dart, and I'm confused about these two methods that Future offers, .then() and .whenCompleted(). What's the main difference between them?

让我们说我想使用 .readAsString()读取.txt,我会这样做:

Lets say I want to read a .txt using .readAsString(), I would do it like this:

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

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

So .then() is like a callback that fires a function once the Future is completed.

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

But I see there is also .whenComplete() that can also fire a function once Future completes. Something like this :

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

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

The difference I see here is that .then() has access to data that was returned! What is .whenCompleted() used for? When should we choose one over the other?

推荐答案

.whenComplete 将在Future是否完成错误时触发一个函数,而不是

.whenComplete will fire a function either when the Future completes with an error or not, instead .then will fire a function after the Future completes without an error.

.whenComplete API引用DOC

Quote from the .whenComplete API DOC

这是最终"块的异步等效项.

This is the asynchronous equivalent of a "finally" block.

这篇关于使用Futures时.then()和.whenCompleted()方法之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆