【发布时间】:2017-09-14 20:53:03
【问题描述】:
需要知道我的函数是否结构良好并正确返回承诺。我正在使用主要条件 if 语句处理新数据和已删除数据。如果数据存在,我正在执行一个数据库集并返回一个承诺return ProposalsRef.child(recipient).set。如果数据不存在,我返回return ProposalsRef.once('value')...。每当触发该函数时,它只会返回一个承诺(这样它就永远不会超时)。另外我在最后实现else{return null;} 只是为了避免超时(不确定这是否是一个好习惯)
exports.ObserveJobs = functions.database.ref("/jobs/{jobid}").onWrite((event) => {
const jobid = event.params.jobid;
if (event.data.exists() && !event.data.previous.exists()) {
const recipient = event.data.child("recipient").val();
if (recipient !== null) {
let ProposalsRef = admin.database().ref(`proposals/${jobid}`);
return ProposalsRef.child(recipient).set({
budget: event.data.child("budget").val(),
description: event.data.child("description").val(),
ischat: false,
isinvitation: true,
timing: event.data.child("timing").val(),
});
};
} else if (!event.data.exists() && event.data.previous.exists()) {
let ProposalsRef = admin.database().ref(`proposals/${jobid}`);
return ProposalsRef.once('value').then(snapshot => {
if (snapshot.hasChildren()) {
const updates = {};
snapshot.forEach(function(child) {
updates[child.key] = null;
});
return ProposalsRef.update(updates);
}
});
}else{
return null;
};
});
我也想知道,假设我必须执行多个数据库操作而不是一个。请参见下面的示例:
return contractRef.once('value').then(snapshot => {
let client = snapshot.child("contractor").val();
let freelancer = snapshot.child("talent").val();
const clientRef = admin.database().ref(`users/${client}`);
const freelancerRef = admin.database().ref(`users/${freelancer}`);
clientRef.child("/account/jobcount").transaction(current => {
return (current || 0) + 1;
});
freelancerRef.child("/account/jobcount").transaction(current => {
return (current || 0) + 1;
});
clientRef.child("/notifications").push({
timestamp: admin.database.ServerValue.TIMESTAMP,
key: contractid,
type: 4
});
freelancerRef.child("/notifications").push({
timestamp: admin.database.ServerValue.TIMESTAMP,
key: contractid,
type: 4
});
});
我只返回return contractRef... 承诺,是否也应返回contractRef 中的承诺(freelancerRef、clientRef)?如果是这样,我应该创建一个承诺数组然后return Promise.all(arrayOfProimises); 或者我可以单独返回承诺return freelancerRef.child("/notifications").push({...
【问题讨论】:
标签: javascript firebase firebase-realtime-database google-cloud-functions