Reputation: 1996
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)
Upvotes: 7
Views: 2643
Reputation: 17289
I think you can use simply:
Future.wait(
[
method1(),
method2(),
]
).then((){});
Upvotes: 0
Reputation: 657148
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.
Upvotes: 14