異步支持
dart 中包含很多返回 Future 和 Stream 對象的方法,這些方法都是一步的,比如 I/O。
async 和 await 關鍵字支持異步編程。
處理 Futures
- 使用 async 和 await
- 使用 Future API,參考Future
//使用 async 修飾方法,使用 await 調用方法
Future checkVersion() async {
var version = await lookUpVersion();
// Do something with version
}
await lookUpVersion();
要使用 await,其方法必須帶有 async 關鍵字,async 方法只會在遇到第一個 await 表達式時纔會執行。
可以使用 try, catch, 和 finally 來處理使用 await 的異常。
try {
server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 4044);
} catch (e) {
// React to inability to bind to the port...
}
可以對一個 async 方法多次使用 await 。
var entrypoint = await findEntrypoint();
var exitCode = await runExecutable(entrypoint, args);
await flushThenExit(exitCode);
await 表達的返回值通常時 Future ,如果不是,則會自動包裝成一個 Futre。 Future 表示承諾返回一個對象,await 表達式會讓程序暫停,知道該對象可用。
聲明異步方法
一個 async 方法是函數體被標記爲 async 的方法。
//同步方法
String lookUpVersion() => '1.0.0';
//異步方法
Future<String> lookUpVersion() async => '1.0.0';
異步方法會返回一個 Future,定義異步方法時不需要使用 Future API,dart會自動創建 Future 對象。
如果異步方法沒有返回值,則需要明確標記返回類型爲 Future<void>
。
處理 Stream
- 使用 async 和 異步循環 await for
- 使用 Stream API,參考Stream
注意:使用 await for 時,要確實需要處理streams的所有結果。例如像UI事件監聽就不需要使用asait for ,因爲UI框架會發送無用的streams。
await for (varOrType identifier in expression) {
// Executes each time the stream emits a value.
}
expression 必須返回 Stream 類型
- 等待,直到 stream 發射一個值
- 使用發射的值,執行循環
- 重複1,2,直到stream關閉
停止監聽一個stream,可以使用 break 或者 return 語句。
async for 確保在 async 方法中使用。
main() async {
...
await for (var request in requestServer) {
handleRequest(request);
}
...
}