db触发器上的firebase函数抛出function返回了未定义的、预期的Promise或值



我的基于实时数据库触发器的firebase函数如下

exports.on_user_created = functions.database.ref("/users/{id}")
.onCreate((change, context) => {
console.log("start of on_user_created ")   
const user = change.val();
console.log("New user:::" + JSON.stringify(user))
const uid = user._uid
const referralCode = user._referralCode
console.log("creating referral node for uid:" + uid + " with code:" + referralCode)
if(referralCode === undefined){
console.error("No referral code created for the user while sign up. Referral node cannot be created.")    
return true
}

var db = admin.database();
var ref = db.ref('referrals')
ref.child(referralCode).set({"uid": uid}).then(
(resp) => {
console.log("referral node created")
return true
}
).catch(
(err) => {
console.error("unable to create referral node on user create:" + err)    
return true  
}
)    
})

它在运行中抛出

5:47:02.035 AM on_user_created  Function returned undefined, expected Promise or value 

我不明白为什么

根据Doug下面的评论改编:"如果没有异步工作要做,通常会返回null">

这是因为您没有返回set()异步操作返回的Promise。

你应该做一些类似的事情:

exports.on_user_created = functions.database.ref("/users/{id}")
.onCreate((change, context) => {
console.log("start of on_user_created ")   
const user = change.val();
console.log("New user:::" + JSON.stringify(user))
const uid = user._uid
const referralCode = user._referralCode
console.log("creating referral node for uid:" + uid + " with code:" + referralCode)
if(referralCode === undefined){
console.error("No referral code created for the user while sign up. Referral node cannot be created.")    
return null  // <-- See Doug's comment below.
}
var db = admin.database();
var ref = db.ref('referrals')
return ref.child(referralCode).set({"uid": uid}).then( // <-- !! Here we return
(resp) => {
console.log("referral node created")
return null
}
).catch(
(err) => {
console.error("unable to create referral node on user create:" + err)    
return null  
}
)    
})

请注意,如果您不需要console.log(),例如用于生产,您可以按如下方式精简代码。

exports.on_user_created = functions.database.ref("/users/{id}")
.onCreate((change, context) => { 
const user = change.val();
const uid = user._uid
const referralCode = user._referralCode
if (referralCode === undefined) {
return null;
} else {
var db = admin.database();
var ref = db.ref('referrals')
return ref.child(referralCode).set({"uid": uid});
}
});

有关在云函数中返回承诺的重要性的更多详细信息,我建议您观看官方视频系列,特别是标题为"学习JavaScript承诺"的视频系列:https://firebase.google.com/docs/functions/video-series/

相关内容

  • 没有找到相关文章

最新更新