2

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?

2
  • The function getUser() is a Future. So obviously the sync statement print(1) will be executed first. Commented Nov 29, 2020 at 16:33
  • if you need to wait for a async function to complete you need to use await , and you can only use the await inside an async function, i guess you are thinking of some over engineering here Commented Nov 30, 2020 at 6:56

1 Answer 1

1

Being able to do what you ask would basically render the distinction between sync and async functions useless (and block the main thread I think). The function you linked "should be considered a last resort".

I think what you want is :

Future<bool> checkUser(String username, String pwd) async { 
  var user = await getUser(username); 
  return user.pwd == encodePwd(pwd) ? true : false;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.