Dart: multiple await for same future
Asked Answered
L

2

7

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)
Lefton answered 25/9, 2018 at 14:27 Comment(0)
D
14

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.

Dorey answered 25/9, 2018 at 14:36 Comment(2)
Well explained.Lefton
Also worth mentioning, even if it is orthogonal to the actual question, is that var login = ensureLogin(); is a lazily initialized variable, so the value of login isn't computed until the first reference to the variable occurs (in functionA).Carrizales
P
0

I think you can use simply:

Future.wait(
  [
    method1(),
    method2(),
  ]
).then((){});
Pachisi answered 14/10, 2021 at 14:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.