Dart异步编程Future

396 阅读1分钟
原文链接: www.jianshu.com

Dart是单线程编程语言,如果执行了阻塞线程代码就会造成程序卡死,异步操作就是为了防止这一现象。 Future类似于ES6中Promise,也提供了then和catchError链式调用。

Future常见用法

  • 使用future.then获取future值or获取异常
  • 通常结合async和await使用
  • future.whenComplete
  • future.timeout
future.then使用

'''
main() {
testFuture().then((value){
print(value);
},onError: (e) {
print("onError: $e");
}).catchError((e){
print("catchError: $e");
});
}

Future<String> testFuture() {
return Future.value("Hello");
// return Future.error("yxjie 创造个error");//onError会打印
// throw "an Error";
}
'''
注:直接throw "an Error"代码会直接异常不会走 catchError方法,因为throw返回的数据类型不是Future<T>类型,then方法onError未可选参数,代码异常时会被调用【代码中有onError回调,catchError不会执行】

async和await使用

'''
import 'dart:async';
test() async {
var result = await Future.delayed(Duration(milliseconds: 2000), ()=>Future.value("hahha"));
print("time = ${DateTime.now()}");
print(result);
}

main() {
print("time start = ${DateTime.now()}");
test();
print("time end= ${DateTime.now()}");

//执行结果:
//time start = 2019-05-15 19:24:14.187961
//time end= 2019-05-15 19:24:14.200480
//time = 2019-05-15 19:24:16.213213
//hahha
}
'''

future.whenComplete使用

此方法类似于java中try{}catch(){}finally{}异常捕获的finally
'''
main() {
Future.error("yxjie make a error")
.then(print)
.catchError(print)
.whenComplete(() => print("Done!!!"));

//执行结果:
//yxjie make a error
//Done!!!
}
'''
以上demo用了方法对象以及插值表达式,不了解方法对象可以参考此文

future.timeout使用

异步操作可能需要很长时间,如访问数据库or网络请求等,我们可以使用timeout来设置超时操作。
'''
main() {
Future.delayed(Duration(milliseconds: 3000), () => "hate")
.timeout(Duration(milliseconds: 2000))
.then(print)
.catchError(print);
//TimeoutException after 0:00:00.002000: Future not completed
}
'''