首页 > 解决方案 > firebase实时数据库触发器中的promise链接问题

问题描述

卡在下面我的代码中的承诺链接。

我的实时数据库有两个节点。用户和订单。我有存储奖励金额的用户。创建新订单时,我有一个订单数据库触发器。我在创建触发器中的要求是从用户节点获取奖励金额并扣除订单金额,然后将新值更新回用户。

exports.on_order_received_deduct_doodle_cash = functions.database.ref("/orders/{id}")
.onCreate((change, context) => {

  const order = change.val();
  const customerObj = order.customer
  const orderObj = order.order
  const afterDiscount = orderObj._afterDiscount
  const uid = customerObj._uid

    var db = admin.database();
    const userRef = db.ref('users/')
    return userRef.child(uid).once("value").then(
        (resp) => {
              const userObj = resp.val()
              const doodleCash = userObj._doodleCash
              console.log("user current doodle cash is::" + doodleCash)
              return doodleCash
        }
    ).then(
        (doodleCash) => {

                if(doodleCash > afterDiscount){
                    const val = doodleCash - afterDiscount
                    return userRef.child(uid).update({"_doodleCash" : val})
                }else{
                    console.error("cannot be a negative value")
                    return null
                }

        }
    ).catch(
        (err) => console.error("something went wrong:" + err)
    )
})

这是将价值从第一个承诺传递给另一个承诺的正确方法吗?

标签: firebasefirebase-realtime-databasepromisegoogle-cloud-functions

解决方案


以下应该可以解决问题。

您应该在您的第一个承诺中返回一个承诺,then()或者返回一个向平台表明 Cloud Function 已完成的值(如null)。

exports.on_order_received_deduct_doodle_cash = functions.database.ref("/orders/{id}")
.onCreate((change, context) => {

  const order = change.val();
  const customerObj = order.customer
  const orderObj = order.order
  const afterDiscount = orderObj._afterDiscount
  const uid = customerObj._uid

    var db = admin.database();
    const userRef = db.ref('users/')
    return userRef.child(uid).once("value").then(
        (resp) => {
              const userObj = resp.val()
              const doodleCash = userObj._doodleCash
              console.log("user current doodle cash is::" + doodleCash)

              if (doodleCash > afterDiscount) {
                    const val = doodleCash - afterDiscount
                    return userRef.child(uid).update({"_doodleCash" : val})
                }else{
                    console.error("cannot be a negative value")
                    return null;
                }
        }
    ).catch(
        (err) => console.error("something went wrong:" + err)
    )
})

推荐阅读