简体   繁体   English

如何在 Dart 中使用 await 而不是 .then()

[英]How to use await instead of .then() in Dart

I'm having the following lines in a Flutter app.我在 Flutter 应用程序中有以下几行。 _devicesRef refers to some node in a Firebase Realtime Database. _devicesRef指的是 Firebase 实时数据库中的某个节点。

_devicesRef.child(deviceId).once().then((DataSnapshot data) async {
    print(data.key);
    var a = await ...
    print(a);
}

These lines work fine.这些线路工作正常。 Now I want to use await instead of .then() .现在我想使用await而不是.then() But somehow, once() never returns.但不知何故, once()永远不会返回。

var data = await _devicesRef.child(deviceId).once();
print(data.key);
var a = await ...
print (a);

So print(data.key) is never called.所以print(data.key)永远不会被调用。

What's wrong here?这里出了什么问题?

It could be explained by the code following your snippet.它可以通过您的代码段后面的代码来解释。 Perhaps the future completion is trigger by something after your code and transforming your code with await will wait until a completion that never happens.也许未来的完成是由您的代码之后的某些东西触发的,并且使用 await 转换您的代码将等到永远不会发生的完成。

For instance, the following code works:例如,以下代码有效:

main() async {
  final c = Completer<String>();
  final future = c.future;
  future.then((message) => print(message));
  c.complete('hello');
}

but not this async/await version:但不是这个异步/等待版本:

main() async {
  final c = Completer<String>();
  final future = c.future;
  final message = await future;
  print(message);
  c.complete('hello');
}

If you intend to use await as a replacement of .then() in your snippet, this is how you can accomplish it:如果您打算在您的代码片段中使用await来替代.then() ,那么您可以通过以下方式实现它:

() async {
    var data = await _devicesRef.child(deviceId).once();
    print(data.key);
    var a = await ...
    print(a);
}();

By placing the code in the asynchronous closure () async {}() , we are not preventing execution of the code that comes after, in a similar fashion to using .then() .通过将代码放在异步闭包() async {}()中,我们不会以类似于使用.then()的方式阻止后续代码的执行。

it should be encased in an async function like this to use await它应该包含在这样的异步函数中以使用 await

Furtre<T> myFunction() async {
  var data = await _devicesRef.child(deviceId).once();
  return data;
}

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

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