I want to call and wait async function done before return from a sync function
// async function
Future<User> getUser(String username) async {
...
}
In dart, i could use https://api.dart.dev/stable/2.9.2/dart-cli/waitFor.html to wait a async function before go to next statement.
bool checkUser(String username, String encodedPwd) {
var user = waitFor<User>(getUser(username));
if (user.pwd == encodedPwd)
return true;
else
return false;
}
Because the require of the framework, the checkUser function will be call by framework, and must be a sync function.
In flutter, I could not use dart:cli, I implement by pattern .then() .whenComplete(), but when call checkUser the statement print(1) will be call and end the function without wait for getUser finish.
bool checkUser(String username, String pwd) {
getUser(username).then((user) {
if (user.pwd == encodePwd(pwd)) {
return true;
} else {
return false;
}
);
print(1);
}
How to call async function inside sync function and wait the async function done before return?
getUser()is a Future. So obviously the sync statementprint(1)will be executed first.await, and you can only use theawaitinside an async function, i guess you are thinking of some over engineering here