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)
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.
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.
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)) .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With