How is whenCompleted() different from then() in Futurs?
How is whenCompleted() different from then() in Futurs?
The whenCompleted()
and then()
methods in Dart's Future
class are used to handle the completion of a Future
, but they have some key differences:
Callback function: then()
takes a callback function that is executed when the Future
completes successfully, while whenCompleted()
takes a callback function that is executed regardless of whether the Future
completes successfully or with an error[1][2].
Return value: then()
returns a new Future
that completes with the return value of the callback function, while whenCompleted()
returns the original Future
that it was called on[1][2].
Error handling: When using then()
, you can chain multiple then()
calls together to handle the result of the previous Future
. If an error occurs in one of the then()
callbacks, it will be passed to the next error handler (either another then()
with an error handler or a catchError()
call). With whenCompleted()
, any errors that occur in the callback function are not propagated to the returned Future
[1][2].
Here's an example to illustrate the differences:
Future<String> fetchData() {
return Future.delayed(Duration(seconds: 2), () => 'Data');
}
void main() {
fetchData()
.then((data) {
prin...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào