我正在探索Dart中的Futures,并且对Future提供的这两种方法感到困惑。它们之间的主要区别是什么?
假设我想使用读取.txt .readAsString()
,我会这样:
void main(){
File file = new File('text.txt');
Future content = file.readAsString();
content.then((data) {
print(content);
});
}
Run Code Online (Sandbox Code Playgroud)
因此.then()
,就像Future完成后触发功能的回调一样。
但是我看到,.whenComplete()
一旦Future完成,也可以触发功能。像这样的东西:
void main(){
File file = new File('text.txt');
Future content = file.readAsString();
content.whenComplete(() {
print("Completed");
});
}
Run Code Online (Sandbox Code Playgroud)
我在这里看到的区别是可以.then()
访问返回的数据!有什么.whenCompleted()
用?什么时候选择一个?
而且还这两个环节上,。那么()和.whenCompleted()在一个页面有实现的结尾:
。然后():
Future<R> then<R>(FutureOr<R> onValue(T value), {Function onError});
Run Code Online (Sandbox Code Playgroud)
.whenCompleted():
Future<T> whenComplete(FutureOr action());
Run Code Online (Sandbox Code Playgroud)
什么Future<R>
意思 还是Future<T>
?我知道Future是一种类型,但是R和T是什么?
谢谢!
.whenComplete会在Future是否完成但没有错误时触发函数,而.then将在Future完成而没有错误时触发函数。
引用.whenComplete API DOC
这是“最终”块的异步等效项。
即使出现错误,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");
});
Run Code Online (Sandbox Code Playgroud)
因此,如果出现错误,则会调用上述所有回调。
归档时间: |
|
查看次数: |
575 次 |
最近记录: |