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.
Advertisements. An asynchronous operation executes in a thread, separate from the main application thread. When an application calls a method to perform an operation asynchronously, the application can continue executing while the asynchronous method performs its task.
Asynchronous function is a function that returns the type of Future. We put await in front of an asynchronous function to make the subsequence lines waiting for that future's result. We put async before the function body to mark that the function support await .
What is Async/Await/then In Dart/Flutter? await is to interrupt the process flow until the async method completes. then however does not interrupt the process flow. This means that the next instructions will be executed. But it allows you to execute the code when the asynchronous method completes.
Marking a function as async
or async*
allows it to use the async
/await
for a Future
.
The difference between both is that async*
will always return a Stream
and offer some syntactical sugar to emit a value through the yield
keyword.
We can therefore do the following:
Stream<int> foo() async* {
for (int i = 0; i < 42; i++) {
await Future.delayed(const Duration(seconds: 1));
yield i;
}
}
This function emits a value every second, which increments every time.
async
gives you a Future
async*
gives you a Stream
.You add the async
keyword to a function that does some work that might take a long time. It returns the result wrapped in a Future
.
Future<int> doSomeLongTask() async {
await Future.delayed(const Duration(seconds: 1));
return 42;
}
You can get that result by awaiting the Future:
main() async {
int result = await doSomeLongTask();
print(result); // prints '42' after waiting 1 second
}
You add the async*
keyword to make a function that returns a bunch of future values one at a time. The results are wrapped in a Stream.
Stream<int> countForOneMinute() async* {
for (int i = 1; i <= 60; i++) {
await Future.delayed(const Duration(seconds: 1));
yield i;
}
}
The technical term for this is asynchronous generator function. You use yield
to return a value instead of return
because you aren't leaving the function.
You can use await for
to wait for each value emitted by the Stream.
main() async {
await for (int i in countForOneMinute()) {
print(i); // prints 1 to 60, one integer per second
}
}
Watch these videos to learn more, especially the one on Generators:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With