【问题标题】:How to use await instead of .then() in Dart如何在 Dart 中使用 await 而不是 .then()
【发布时间】:2019-05-14 06:22:13
【问题描述】:

我在 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) 永远不会被调用。

这里有什么问题?

【问题讨论】:

  • 你是在一个方法中调用 await _devicesRef.child ... 吗?
  • Future<void> generateSomeId() async { ... }
  • 嗯,奇怪,应该能用,你知道有没有数据吗?
  • 99% 没有。我想创建一个 ID 并检查该 ID 是否已存在于数据库中。所以我创建了一个随机字符串并尝试获取这个节点。如果存在,我必须创建一个新 ID。如果它不存在,那么我会将它添加到数据库中。所以更多的是检查一个节点是否已经存在。

标签: firebase-realtime-database dart flutter


【解决方案1】:

这可以通过您的 sn-p 后面的代码来解释。也许未来的完成是由您的代码之后的某些东西触发的,并且使用 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');
}

【讨论】:

    【解决方案2】:

    如果您打算在您的 sn-p 中使用 await 代替 .then(),您可以通过以下方式完成它:

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

    通过将代码放在异步闭包() async {}() 中,我们不会阻止执行后面的代码,类似于使用.then()

    【讨论】:

      【解决方案3】:

      它应该被封装在这样的异步函数中以使用等待

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

      【讨论】:

        猜你喜欢
        • 2019-08-17
        • 2022-01-19
        • 2020-10-30
        • 2020-06-19
        • 2020-11-26
        • 1970-01-01
        • 1970-01-01
        • 2018-06-18
        • 2016-02-18
        相关资源
        最近更新 更多