Open In App

Using await async in Dart

The async and await approaches in Dart are very similar to other languages, which makes it a comfortable topic to grasp for those who have used this pattern before. However, even if you don’t have experience with asynchronous programming using async/await, you should find it easy to follow along here. 

Async functions:

Functions form the base of asynchronous programming. These async functions have async modifiers in their body. Here is an example of a general async function below:



When an async function is called, a Future is immediately returned and the body of the function is executed later. As the body of the async function is executed, the Future returned by the function call will be completed along with its result. In the above example, calling demo() results in the Future. 

Any functions you want to run asynchronously need to have the async modifier added to it. This modifier comes right after the function signature, like this:






void hello() async {
  print('something exciting is going to happen here...');
}

Typically, the function you want to run asynchronously would have some expensive operation in it like file I/O (an API call to a RESTful service).

Await expressions:

Await expressions makes you write the asynchronous code almost as if it were synchronous. In general, an await expression has the form as given below:




void main() async {
  await hello();
  print('all done');
}

Typically, it is an asynchronous computation and is expected to evaluate to a Future. The await expressions evaluate the main function, and then suspends the currently running function until the result is ready–that is, until the Future has completed. The result of the await expression is the completion of the Future.

Futures:

Dart is a single-threaded programming language. Future<T> object represents the result of an asynchronous operation which produces a result of type T. If the result is not usable value, then the future’s type is Future<void>. A Future represents a single value either a data or an error asynchronously

There are 2 ways to handle Futures:

Now, Let’s write a program and see the output.

Example:




Future delayedPrint(int seconds, String msg) {
  final duration = Duration(seconds: seconds);
  return Future.delayed(duration).then((value) => msg);
}
main() async {
  print('Life');
  await delayedPrint(2, "Is").then((status){
    print(status);
  });
  print('Good');
}

Output-

Life
Is
Good

In this case, we used async and await keywords. Await basically holds the control flow, until the operation completes. To use await within a function, we have to mark the function by async keyword. Which means, this function is an asynchronous function.

Combined with the Futures class, the async / await pattern in Dart is a powerful and expressive way of doing asynchronous programming.


Article Tags :