Google News
logo
Dart - Interview Questions
What is the purpose of the "async" and "await" keywords in Dart?
In Dart, the "async" and "await" keywords are used in conjunction to handle asynchronous operations and make asynchronous code more readable and manageable. Here's an explanation of each keyword and their purpose:

1. async : The "async" keyword is used to mark a function as asynchronous. An asynchronous function can perform time-consuming operations without blocking the execution of other code. It allows you to write code that appears synchronous even though it may involve asynchronous tasks.

   When you mark a function as "async," it means that the function can use the "await" keyword to pause its execution and wait for asynchronous operations to complete. Asynchronous functions return a Future object that represents the eventual completion of the function's execution.

2. await : The "await" keyword is used within an asynchronous function to pause its execution until a Future completes and returns a result. It can only be used inside an "async" function. When an "await" expression is encountered, the function is temporarily suspended, allowing other code to execute.

   The "await" keyword is typically used before an asynchronous operation, such as making an HTTP request, reading from a file, or querying a database. It allows you to write code that waits for the completion of the asynchronous task before proceeding.

   By using "await," you can write asynchronous code that looks and behaves more like synchronous code, making it easier to read, understand, and reason about asynchronous operations.

Here's an example that demonstrates the usage of "async" and "await":
import 'dart:io';

void main() async {
  print('Start');
  await performTask();
  print('End');
}

Future<void> performTask() async {
  print('Task started');
  await Future.delayed(Duration(seconds: 2));
  print('Task completed');
}​
In the example above, the `main` function is marked as "async," which allows it to use the "await" keyword. Inside the `main` function, we call the `performTask` function using "await," which suspends the execution of the `main` function until the `performTask` function completes.

The `performTask` function is also marked as "async" and returns a `Future<void>`. Inside the `performTask` function, we use `await` before `Future.delayed` to pause the execution of the function for 2 seconds, simulating a time-consuming task. Once the delay completes, the function resumes, and the remaining code is executed.

When you run the above code, it will output :
Start
Task started
Task completed
End​

The use of "async" and "await" simplifies the code by eliminating the need for callback functions or chaining promises. It allows you to write asynchronous code in a more sequential and readable manner, making it easier to handle asynchronous operations and avoid callback hell.
Advertisement