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 } 複製代碼