await 表达式只能在异步函数中使用

Posted

技术标签:

【中文标题】await 表达式只能在异步函数中使用【英文标题】:The await expression can only be used in an async function 【发布时间】:2020-05-26 00:51:31 【问题描述】:

我正在尝试在用户登录时从 Firestore 加载一些数据,并且需要等到数据加载完毕才能继续。但是,我等待结果的努力没有奏效。

Future<bool> userListener() async 
  _auth.onAuthStateChanged.listen((firebaseUser) 
    bool isDone = false; 

    if (firebaseUser != null) 
      isDone = await loadUserData(firebaseUser);   // This line is killing me!!
      return isDone;
     else 
      return false;
    
  , onError: (error) 
    print('error in UserListener: $error');
  );


Future<bool> loadUserData(FirebaseUser user) async 
  Firestore database = Firestore();
  DocumentReference data = database.collection('userData').document(user.uid);

  try 
    DocumentSnapshot myQuery = await data.get();
    theNumber = myQuery.data['theNumber'];
    return true;
   on PlatformException catch (e) 
    print(e);
    return false;
  

我从这行得到一个可爱的错误:

 isDone = await loadUserData(firebaseUser);

”。

我不确定这些函数如何变得更加异步。此外,如果我不添加await,那么我会被告知不能将 Future 分配给 bool,这非常有意义,并向我建议我的函数实际上是异步的。

为什么我不能等待 loadUserData 函数的结果?

【问题讨论】:

【参考方案1】:

该行的主要功能是传递给 onAuthStateChanged 的​​侦听。此功能也应该是异步的,如下所示

  _auth.onAuthStateChanged.listen((firebaseUser) async

【讨论】:

谢谢。现在这似乎非常明显。【参考方案2】:

如果你调用的是异步函数,你的调用函数也应该是异步的。

将 async 关键字添加到您的函数中。变化:

void main (List<String> arguments)

到:

void main (List<String> arguments) async

例子:

Future<void> main (List<String> arguments) async 
  var done = await readFileByteByByte(); // perform long operation


Future<void> main(List<String> arguments) 
  readFileByteByByte().then((done) 
    print('done');
  );
  print('waiting...');
  print('do something else while waiting...');

【讨论】:

以上是关于await 表达式只能在异步函数中使用的主要内容,如果未能解决你的问题,请参考以下文章

async await进行异步处理

async await进行异步处理

JS async和await关键字

使用 async/ await 进行 异步 编程

async和await用法

用 async/await 来处理异步