Asynchronous Programming
Asynchronous Programming In Dart
Asynchronous programming says Don't wait for us, We will call you back.
It fits well with an event-driven program. Let’s first understand synchronous programming.
What Is Synchronous Programming
In Synchronous programming, the program is executed line by line, one at a time. Synchronous operation means a task that needs to be solved before proceeding to the next one.
Example Of Synchronous Programming
main() {
print("First Operation");
print("Second Big Operation");
print("Third Operation");
print("Last Operation");
}
Here in this example, you can see that it will print line by line. Let’s suppose Second Big Operation
takes 3 seconds to load then Third Operation
and Last Operation
need to wait for 3 seconds. To solve this issue asynchronous programming is here.
Asynchronous Programming
In Asynchronous programming, program execution continues to the next line without waiting to complete other work. It simply means Don't wait
. It represents the task that doesn’t need to solve before proceeding to the next one.
Note: Asynchronous Programming improves the responsiveness of the program.
Example Of Asynchronous Programming
main() {
print("First Operation");
Future.delayed(Duration(seconds:3),()=>print('Second Big Operation'));
print("Third Operation");
print("Last Operation");
}
Here in this example, you can see that it will print Second Big Operation
at last. It is taking 3 seconds to load and Third Operation
and Last Operation
don’t need to wait for 3 seconds. This is the problem solved by Asynchronous Programming. A Future represents a value that is not yet available, we will learn it below:
Why We Need Asynchronous
- To Fetch Data From Internet,
- To Write Something to Database,
- To Read Data From File, and
- To Download File etc.
Note: To Perform asynchronous operations in dart you can use the Future
class and the async
and await
keywords. We will learn Future, Async, and Await later in this guide.
Important Terms
Synchronous
operation blocks other operations from running until it completes.Synchronous
function only perform a synchronous operation.Asynchronous
operation allows other operations to run before it completes.Asynchronous
function performs at least one asynchronous operation and can also perform synchronous operations.
Note: We cannot perform an asynchronous operation from a synchronous function.