【问题标题】:Cloud Functions: How to handle .then() for task accomplished or not accomplished?Cloud Functions:如何处理 .then() 完成或未完成的任务?
【发布时间】:2020-10-06 01:39:31
【问题描述】:

如果ref 中有要删除的节点,我正在尝试更新节点.child("Merchans").child(userId).child(merchanId) 中的status 值。

但是remove().then()返回的promise总是undefined无论节点是否存在。

exports.cancelAnnouncements = functions.database
.ref('Cancelads/{userId}')
.onCreate((snapshot, context) => {
  const userId = context.params.userId;

  const targetCountry = snapshot.val().country;
  const targetState = snapshot.val().state;
  const startTime = snapshot.val().ini;
  const merchanId = snapshot.val().merchanId;
  const status = snapshot.val().status;

  var ref;
  if (status === 1) {
    const targetRegion = getTargetRegion(targetCountry, targetState);
    ref = admin.database().ref()
    .child('Queue')
    .child(targetRegion)
    .child(startTime.toString())
    .child(merchanId);

    console.log("inside queue");
  } else if (status === 2) {
    ref = admin.database().ref()
    .child('Announcements')
    .child(targetCountry)
    .child(targetState)
    .child(merchanId);

    console.log("inside announcements");
  }

  return ref.remove().then((result) => {
    if (result === null || result === undefined) return console.log("RESULT IS NULL OR UNDEFINED", result);
    return admin.database().ref()
    .child("Merchans")
    .child(userId)
    .child(merchanId)
    .update({status: 3});
  })
  .catch(error => {
    return console.log("error", error);
  });

});

我的问题是:如何检查节点是否被删除?因为在节点不存在的情况下不会调用.catch()块。

【问题讨论】:

    标签: node.js firebase-realtime-database google-cloud-functions


    【解决方案1】:

    如果最终结果是节点不存在,则认为 Firebase 上的删除操作已成功。这意味着执行remove操作时节点不存在时操作成功。

    如果你想确定你的代码主动移除了节点,你必须use a transaction,它首先读取节点,然后根据当前值设置它的新值。

    【讨论】:

      【解决方案2】:

      正如@Frank van Puffelen 提到的,首先我们必须执行读取操作来检查节点是否存在。

      然后,我们可以执行我们希望的操作。当然,这个额外的操作会增加你的账单。

      以下是我用于完成此任务的代码。

      return ref.once('value').then(dataSnapshot => {
          if (dataSnapshot.val() !== null) {
            const promise1 = snapshot.ref.remove();
            const promise2 = dataSnapshot.ref.remove();
            const promise3 = admin.database().ref()
            .child("Merchans").child(userId).child(merchanId).update({status: 3});
      
            console.log('dataSnapshot exists; removing and updating status', dataSnapshot.val());
            return Promise.all([promise1, promise2, promise3]);
            //return dataSnapshot.ref.remove();
          }
          console.log('dataSnapshot is NULL', dataSnapshot.val());
          return snapshot.ref.remove();
        });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多