Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: multiple await for same future

I have recently seen some code example like below

Future<Null> ensureLogin() {...}

var login = ensureLogin();

Future functionA() async {
   await login;
   print("FunctionA finished");
}

Future functionB() async {
   await login;
   print("FunctionB finished");
}

void main() {
   functionA();
   functionB()
}

When the future completed, it prints out below:

FunctionA finished
FunctionB finished

Looks like we can have multiple await for the same future object? But how does this work under the hood? And what is it equivalent to Future? Maybe something like below?

login.then(functionA).then(fucntionB)
like image 658
Panda World Avatar asked Sep 25 '18 14:09

Panda World


People also ask

How do you wait for Future to complete Dart?

Sometimes you need to have results of multiple async functions before starting to work on something else. To prevent multiple awaits, chaining futures in . then(), you can simply use Future. wait([]) that returns an array of results you were waiting for.

What is synchronous and asynchronous in Dart?

synchronous operation: A synchronous operation blocks other operations from executing until it completes. synchronous function: A synchronous function only performs synchronous operations. asynchronous operation: Once initiated, an asynchronous operation allows other operations to execute before it completes.

What is Future data type in Dart?

A Future is used to represent a potential value, or error, that will be available at some time in the future. Receivers of a Future can register callbacks that handle the value or error once it is available. For example: Future<int> future = getFuture(); future. then((value) => handleValue(value)) .


1 Answers

You can register as many callbacks as you want with then(...) for a single Future instance.

Without async/await it would look like

Future functionA() async {
   login.then((r) {
     print("FunctionA finished");
   });
}

Future functionB() async {
   login.then((r) {
     print("FunctionB finished");
   });
}

When login completes, all registered callbacks will be called one after the other.

If login was already completed when login.then((r) { ... }) is called, then the callback is called after the current sync code execution is completed.

like image 66
Günter Zöchbauer Avatar answered Sep 21 '22 05:09

Günter Zöchbauer