问题
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