简体   繁体   English

如何调用和等待异步 function 在 flutter 中同步 function 完成

[英]How to call and wait async function done inside sync function in flutter

I want to call and wait async function done before return from a sync function我想在从同步 function 返回之前调用并等待异步 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. 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.由于框架的要求,checkUser function 将被框架调用,并且必须是同步的 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.在 flutter 中,我无法使用 dart:cli,我通过 pattern.then().whenComplete() 实现,但是当调用 checkUser 时,将调用语句 print(1) 并结束 ZC1C425268E68385D1AB5074C17A9.F

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.我的问题是如何在同步 function 中调用异步 function 并等待异步 function 完成后再返回。

Thank you.谢谢你。

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" .您链接的 function “应该被视为最后的手段”

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

This can be achieved by creating a task, then waiting/yielding for the task to complete.这可以通过创建任务,然后等待/让步以完成任务来实现。 The Yield prevents blocking. Yield 可防止阻塞。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM