Difference between .then() and .whenCompleted() methods when working with Futures?

我怕爱的太早我们不能终老 提交于 2021-01-26 03:11:06

问题


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?

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

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

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

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?


回答1:


.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.

Quote from the .whenComplete API DOC

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




回答2:


.whenComplete = The function inside .whenComplete is called when this future completes, whether it does so with a value or with an error.

.then = Returns a new Future which is completed with the result of the call to onValue (if this future completes with a value) or to onError (if this future completes with an error)

Read detail on API DOC

whenComplete then




回答3:


Even if there is an error, then can still be invoked, provided you have specified 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");
});

So, if there is an error, all the above callbacks gets called.



来源:https://stackoverflow.com/questions/55381236/difference-between-then-and-whencompleted-methods-when-working-with-future

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!