firebase - 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)
)
})
这是将价值从第一个承诺传递给另一个承诺的正确方法吗?
解决方案
以下应该可以解决问题。
您应该在您的第一个承诺中返回一个承诺,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)
)
})
推荐阅读
- python - 在 python 中使用请求模块连接到 Azure-Datalakes-gen2 时遇到问题
- sql - 为什么我需要在这个子选择中硬编码子句?
- python - 如何将大型 python 模型应用于 pyspark-dataframe?
- c# - 具有多个接口的 Autofac Open Generic Decorator 导致循环依赖解析
- android - 不能在没有 PlayStore 的情况下使用 PackageInstaller
- neural-network - 同时训练DDQN
- c - 关于 C 中的内存
- c++ - 如何解决:“const char *”类型的参数与“char *”类型的参数不兼容?
- spring-cloud - 为什么在运行时忽略属性值“management.endpoint.health.show-details”的变化?
- kubernetes - prometheus 监控 eks (aws) 节点