- Dart 和 JavaScript 共同点是——单线程,同步代码会阻塞程序。
- 因此程序里有大量的异步操作,它是用
Future
对象来执行相关操作的,并且在async
函数使用await
关键字时才被执行,直到一个Future操作完成。 - Future 支持链式操作,可以按顺序执行异步函数
1.Future简介
是一个Future 自身的泛型对象 Future<T>
对象。
- 返回的是一个延迟计算的Future对象
- 它将要操作的事件放入EventQueue中,在队列中的事件按照先进先出的原则去注意处理,处理完成后将结果返回给Future对象
- 在这个过程中涉及到了异步和等待 (
async
不阻塞当前线程 和await
延迟执行 )
async和await
getData() async{
return await http.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
}
//然后调用函数来获取结果
String data = getData();
单线程
一旦一个函数开始执行,就必须将这个函数执行完,才能去执行其他函数。
Dart中没有线程的概念,只有isolate,每个isolate都是隔离的,并不会共享内存。一个Dart程序是在Main isolate中的main函数开始,而在Main函数结束后,Main isolate线程开始一个个(one by one)的处理Event Queue中的每一个Event。

2.Future的使用
future里面有几个函数:
then
:异步操作逻辑在这里写。
whenComplete
:异步完成时的回调。
catchError
:捕获异常或者异步出错时的回调。
void testFuture(){
Future future = new Future(() => null);
future.then((_){
print("then");
}).catchError((_){
print("catchError");
}).whenComplete((){
print("whenComplete");
});
}
2.1常用的Future构造函数
new Future((){
// doing something
});
2.2将一个大任务拆成很多小任务一步步执行时,就需要使用到Future.then函数来拆解任务
void main(){
new Future(() => futureTask) // 异步任务的函数
.then((m) => "futueTask execute result:$m") // 任务执行完后的子任务
.then((m) => m.length) // 其中m为上个任务执行完后的返回的结果
.then((m) => printLength(m))
.whenComplete(() => whenTaskCompelete); // 当所有任务完成后的回调函数
}
int futureTask() {
return 21;
}
void printLength(int length) {
print("Text Length:$length");
}
void whenTaskCompelete() {
print("Task Complete");
}
2.3 延迟执行
new Future.delayed(const Duration(seconds: 1), () => futureTask);
网友评论