Dart是单线程编程语言,若是执行了阻塞线程代码就会形成程序卡死,异步操做就是为了防止这一现象。 Future相似于ES6中Promise,也提供了then和catchError链式调用。java
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类型,then方法onError未可选参数,代码异常时会被调用【代码中有onError回调,catchError不会执行】数据库
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 } 复制代码
此方法相似于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用了方法对象以及插值表达式,不了解方法对象能够参考此文bash
异步操做可能须要很长时间,如访问数据库or网络请求等,咱们能够使用timeout来设置超时操做。markdown
main() { Future.delayed(Duration(milliseconds: 3000), () => "hate") .timeout(Duration(milliseconds: 2000)) .then(print) .catchError(print); //TimeoutException after 0:00:00.002000: Future not completed } 复制代码