在 《异步-async和await》 小节中,提到过一个异步函数,会返回一个 Future 对象,它持有了异步函数的返回结果。github
本篇文章,就来认识一下 Future 吧。bash
Future 是在将来某个时间得到想要对象的一种手段。异步
以上是 Future 的定义。async
简单来讲,就是咱们可以经过它在某个时间点得到异步任务中返回的值。函数
实际上,就是给 Future 设置回调函数,当异步任务执行完成后,会调用回调函数。post
Future<T> login = new Future<T>(() {
...
return t;
});
login.then((t){
//..
})
复制代码
当异步的 login 任务执行完成后,回调用 then()
中的回调函数。ui
Future.then()
spa
任务执行完成会进入这里,可以得到返回的执行结果。3d
Future.catchError()
有任务执行失败,能够在这里捕获异常。
Future.whenComplete()
当任务中止时,最后会执行这里。
Future.wait()
能够等待多个异步任务执行完成后,再调用 then()
。
只有有一个执行失败,就会进入 catchError()
。
Future.delayed()
延迟执行一个延时任务。
这是一个例子:
Future.wait([
// 2秒后返回结果
Future.delayed(new Duration(seconds: 2), () {
return "hello";
}),
// 4秒后返回结果
Future.delayed(new Duration(seconds: 4), () {
return " world";
})
]).then((results) {
//执行成功会走到这里
print(results[0]+results[1]);
}).catchError((e){
//执行失败会走到这里
print(e);
}).whenComplete((){
//不管成功或失败都会走到这里
});;复制代码