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 千次以上浏览

开启你的事业

完成该课程以获得认证

开始
广告
© . All rights reserved.