【问题标题】:Setting function parameter inside then block with firestore在里面设置函数参数然后用firestore块
【发布时间】:2018-11-06 20:08:01
【问题描述】:

所以我试图在处理 firestore 时在 then 块中设置一个对象参数,但由于某种原因它没有被设置。我的语法有问题吗?我认为使用=> 可以让我这样做。

updateLedger(id: string, data: any) {
    this.afs.collection('chartofaccounts').doc(id).ref.get().then(doc => {
      if (doc.data().normalside === 'debit') {
        ///// set the runningBalance of the data object passed into the function here
        data.runningBalance = doc.data().debitAmount - doc.data().creditAmount;
      } else {
        ///// or here...
        data.runningBalance = doc.data().creditAmount - doc.data().debitAmount;
      }
    });
    return this.afs.collection('ledger').add(data);
  }

【问题讨论】:

  • 我怀疑是因为您在异步操作完成之前尝试使用data
  • @amy 那么如何设置runningBalance 属性?
  • 您不必同步返回,而是使用承诺或回调,因为您正在添加尚未设置 runingBalance 的数据...
  • @V.Sambor 那我该怎么做呢?
  • 我会写一个可能的例子来回答

标签: javascript google-cloud-firestore


【解决方案1】:

这是一种可能的方法,但我不确定你是否真的需要回调,重要的想法是在承诺解决(异步)时在 .then 中添加 this.afs.collection('ledger').add(data); 这一行。我也把回调给你看看是否有帮助。

updateLedger(id: string, data: any, callback: function) {
  this.afs.collection('chartofaccounts').doc(id).ref.get().then(doc => {
    if (doc.data().normalside === 'debit') {
      ///// set the runningBalance of the data object passed into the function here
      data.runningBalance = doc.data().debitAmount - doc.data().creditAmount;

      // You set it here maybe you don't even need the callback
      this.afs.collection('ledger').add(data);
      callback(data);
    } else {
      ///// or here...
      data.runningBalance = doc.data().creditAmount - doc.data().debitAmount;

      // You set it here maybe you don't even need the callback
      this.afs.collection('ledger').add(data);
      callback(data);
    }
  });
}

// In the call you receive the result
updateLedger(id, data, (resultData) => {
  console.log(resultData)
})

确保then被调用,如果没有,添加.catch语句,也许还有一些其他问题......

【讨论】:

    猜你喜欢
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 2020-11-29
    • 2018-03-09
    • 1970-01-01
    相关资源
    最近更新 更多