如何在Dart中使用await代替.then()

时间:2018-12-13 04:26:28

标签: firebase-realtime-database dart flutter

我在Flutter应用中包含以下几行。 _devicesRef是指Firebase实时数据库中的某个节点。

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

这些行工作正常。现在,我要使用await而不是.then()。但是以某种方式,once()再也不会返回。

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

因此从未调用print(data.key)

这是怎么了?

3 个答案:

答案 0 :(得分:3)

代码段后面的代码可以解释这一点。也许将来的完成是由代码之后的某些事情触发的,并且用await转换代码将等待直到永远不会发生的完成。

例如,以下代码有效:

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

但不是此异步/等待版本:

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

答案 1 :(得分:2)

如果您打算在代码段中使用await来代替.then(),则可以通过以下方法来实现:

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

通过将代码放置在异步闭包() async {}()中,我们不会像使用.then()那样阻止执行后续代码。

答案 2 :(得分:-1)

应将其封装在这样的异步函数中,以使用await

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