What is "await" in Dart?

Thu, Dec 8, 2022

Read in 2 minutes

In this post we learn about "await" keyword in Dart.

In Dart, the await keyword is used to pause the execution of an asynchronous function until a value is returned from an asynchronous operation. An asynchronous operation is a task that can be performed in the background, such as a network request or a file I/O operation.

When an asynchronous function is called, it returns a Future object that represents a value that will be available in the future. The await keyword is used to wait for the Future object to complete and return its value. When the value is returned, the function resumes execution.

Here’s an example of using the await keyword to wait for a Future object to complete:

Future<String> fetchUserData() {
  return Future.delayed(Duration(seconds: 1), () => 'User data');
}

void main() async {
  String userData = await fetchUserData();

  print(userData);
}

In this example, we define a function called fetchUserData that returns a Future object that contains a String value. The Future object is created using the Future.delayed constructor, which delays the execution of the function by one second. When the delay is complete, the function returns the string 'User data'.

In the main function, we call the fetchUserData function using the await keyword to wait for the Future object to complete and return its value. When the value is returned, it is assigned to the userData variable, and the value is printed to the console.

The await keyword can also be used with try/catch blocks to handle errors that occur during asynchronous operations. Here’s an example:

Future<String> fetchUserData() {
  return Future.delayed(Duration(seconds: 1), () => throw Exception('Error fetching user data'));
}

void main() async {
  try {
    String userData = await fetchUserData();

    print(userData);
  } catch (e) {
    print(e);
  }
}

In this example, the fetchUserData function throws an exception to simulate an error that occurs during an asynchronous operation. In the main function, we use a try/catch block to handle the error that is thrown by the fetchUserData function. The catch block is executed if an error occurs, and the error message is printed to the console.

The await keyword is an essential feature of Dart’s concurrency model. It allows developers to write efficient and responsive programs that can perform time-consuming operations without blocking the user interface.


Shohruh AK



Category:

Dart

Tags:



See Also

What is "async" in Dart?
What is "assert" in Dart?
What is "as" in Dart language?
What is "abstract" in Dart language?
Everything you need to know about Dart language