Dart 程式設計中的 Async 和 Await


Async 和 Await 關鍵字用於提供宣告式的方法來定義非同步函式並使用其結果。

如果我們想將函式宣告為非同步函式,則使用async 關鍵字await 關鍵字僅用於非同步函式。

語法

void main() async { .. }

如果函式具有已宣告的返回型別,則將 Future<T> 的型別更新為返回型別。

Future<void> main() async { .. }

最後,當我們希望等待非同步函式完成時,可以使用 await 關鍵字。

await someAsynchronousFunction()

示例

讓我們考慮一個示例,其中我們藉助 async 關鍵字聲明瞭 main 函式,然後使用 await 關鍵字等待非同步結果。

Future<void> printDelayedMessage() {
   return Future.delayed(Duration(seconds: 4), () => print('Delayed Output.'));
}
void main() async {
await printDelayedMessage(); // will block the output until the asynchronous result
print('First output ...');
}

輸出

Delayed Output.
First output ...

示例

讓我們考慮另一個完整的示例,其中我們同時使用了 async 和 await 關鍵字。

考慮以下所示的示例 -

void main() async {
   var userEmailFuture = getUserEmail();
   // register callback
   await userEmailFuture.then((userEmail) => print(userEmail));
   print('Hello');
}
// method which computes a future
Future<String> getUserEmail() {
   // simulate a long network call
   return Future.delayed(Duration(seconds: 4), () => "mukul@tutorialspoint.com");
}

輸出

mukul@tutorialspoint.com
Hello

更新日期: 2021 年 5 月 21 日

1 千次以上瀏覽

開啟你的事業

完成該課程以獲得認證

開始
廣告