Async and Await in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

Async and Await keywords are used to provide a declarative way to define the asynchronous function and use their results.

The async keyword is used when we want to declare a function as asynchronous and the await keyword is used only on asynchronous functions.

Syntax

void main() async { .. }

If the function has a declared return type, then update the type of the Future<T> to the return type.

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

And finally, we make use of await keyword when we want to wait for the asynchronous function to finish.

await someAsynchronousFunction()

Example

Let's consider an example where we are declaring the main function with the help of the async keyword and then wait for an asynchronous result using the await keyword.

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 ...');
}

Output

Delayed Output.
First output ...

Example

Let's consider one more complete example where we make use of both the async and await keyword.

Consider the example shown below −

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");
}

Output

mukul@tutorialspoint.com
Hello
raja
Published on 21-May-2021 12:16:28
Advertisements