Dart(八)Future、async、await異步
同步方法
Dart通常是單線程執行:
如:
String method1() { return "1"; } String method2() { return "2"; } String method3() { return "3"; } void testA() { print(method1()); print(method2()); print(method3()); }
則輸出:
1
2
3
異步方法
如果是執行的網絡請求、訪問數據庫或文件等,那么方法不會立刻返回結果,需要一定的執行時間。這時不能一直等待,時間長了就ANR了。
這種情況,可以用Future描述未來的結果。
如:
// 假設method1是網絡請求 Future<String> f1 = new Future(method1);//此時f1就是未來的結果 // 未來的結果獲取,使用then f1.then((String value) { print("value1=$value"); });
async 與await 將異步方法按同步方法操作
- async 描述一個執行異步操作的方法
- await 表示一直等待異步方法返回結果,才繼續往后執行
如:
Future<String> method5() async { return "5"; } void testD() async { method1(); String f5 = await method5(); print(f5); method3(); }
結果:
1
5
3
wait 並行執行
同時執行了多個網絡請求,等所有結果都返回后再執行操作,返回一個List的結果集。
如:
Future<String> method5() async { return "5"; } Future<String> method6() async { return "6"; } Future<String> method7() async { return "7"; } void testE() { Future.wait([method5(), method6(), method7()]).then((List responses) { print(responses); }).catchError((e) { print(e); }); }
結果:
[5,6,7]
鏈式調用
多個網絡請求,后者需要前者的返回值當作參數,最后一個才是想要的值。
如:
Future<int> method8() async { return 8; } Future<int> method9(int p) async { return p+9; } Future<int> method10(int p) async { return p+10; } void testG() { method8().then((value8) { print("value8=$value8"); return method9(value8); }).then((value9) { print("value9=$value9"); return method10(value9); }).then((value10) { print("value10=$value10"); }); }
結果:
value8=8
value9=17
value10=27