【问题标题】:Does a function that calls a Future needs to be a Future too?调用 Future 的函数也需要是 Future 吗?
【发布时间】:2021-11-23 04:35:53
【问题描述】:

我有一个调用 Future 的函数。现在我不确定第一个函数是否也需要成为未来来等待数据。这是我的代码:

  FireBaseHandler handler = FireBaseHandler();

  saveRows() {
    handler.saveRows(plan.planId, plan.rows); ///this is a future
  }

在我的 FireBaseHandler 类中,我有这个 Future:

  final CollectionReference usersCol =
      FirebaseFirestore.instance.collection('users');

  Future saveRows(String id, data) async {
    return await usersCol.doc(myUser.uid).collection('plans').doc(id)
        .update({'rows': data});
  }

那么第一个函数也需要是 Future 吗?

【问题讨论】:

    标签: flutter dart google-cloud-firestore future


    【解决方案1】:

    您可以在 sync 函数中包含 async 函数。但是这样你就失去了await 的能力。并且await 只允许在标记为async 的函数中使用,这导致我们作为该函数的结果到达Future。所以,是的,如果你需要等待结果,两个函数都必须是 Future 函数。

    编辑: 如果你需要你的包装函数是sync,但仍然能够从内部async 函数中检索结果,你可以使用回调:

      saveRows(Function(dynamic) callback) {
        handler.saveRows(plan.planId, plan.rows).then((result){
          callback(result);
    });
      }
    

    这样调用函数后的任何时间点都会检索到结果(代码不是awaited)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-10
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-02
      • 2019-05-18
      相关资源
      最近更新 更多