0
votes

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);
}

My question is how to call async function inside sync function and wait the async function done before return.

Thank you.

2
The function getUser() is a Future. So obviously the sync statement print(1) will be executed first. - Prasanna Kumar
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 - Yadu

2 Answers

0
votes

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;
}
0
votes

This can be achieved by creating a task, then waiting/yielding for the task to complete. The Yield prevents blocking.

    var result = MyAsyncMethod.InvokeAsync(data);
    result.Start();

    while (result.Status != TaskStatus.RanToCompletion)
    {
        System.Threading.Thread.Yield();
    }