A visualisation guide to Dart’s async-await pattern
I’m a new comer to Dart programming language, and the async-await
pattern in modern languages in general. So here are some visualisations that explain how it works under the hood for Dart newbies like me.
Since my background is mainly from the Java6 and Python. I’m used to doing asynchronous programming the “old school” ways of creating a thread pool and submitting a job to it, or creating a thread object, overriding its run()
method and starting it. You know, the “fun” stuff. So the concept of async-await
and handling of the corresponding Future
object was a bit confusing to me. After spending hours digging into the official documentations here and here, a couple more StackOverflow questions and debugging real issues on a project I’m working on, these are some simple visualisations of its key concepts. Hopefully they add more clarity to those of you who find official documentations are somewhat a bit vague.
The async function
Let’s say we have an asycn
function
Future func1() async {
// some expensive logics
}
Calling func1()
always executes on a new thread and return a Future
object, which is like a handle to the caller thread to check on the status of the new thread. Once the execution of func1()
is completed, the result is returned and the Future
object’s connectionState
will be set to done
. However the behaviour on the current calling thread depends on how you call it.
Blocking call
Calling func1()
spawns a new thread and blocks the calling thread until that new thread executing func1()
returns.
var x = await func1();
Non-blocking call
Calling func1()
without the await
keyword spawns a new thread, but does not wait. The caller thread then continues on whatever it has to do next.
Future future = func1();
Chaining of Futures
Adding then(func2())
on the returned Future
is basically telling the new thread that executes the func1()
to spawn another new thread to execute the func2()
once done.
Lastly, keep in mind that it is not necessary to explicitly have the await
keyword within the body of an async
function. The function is always executed in a new thread. However the function encapsulating any await
keyword must be declared async
.
That’s all there is to it. Hope it’s helpful to you, and do let me know if I’ve understood anything incorrectly here.