需要知道我的功能是否結構良好並正確地返回承諾。我正在使用主條件if語句處理新的和刪除的數據。如果數據存在,我正在執行一個數據庫集並返回一個承諾return ProposalsRef.child(recipient).set
。如果數據不存在,我將返回return ProposalsRef.once('value')...
。只要函數被觸發,它將只返回一個承諾(這種方式永遠不應該超時)。我也是實現一個else{return null;}
在剛剛結束來避免超時(不知道這是一個很好的做法)firebase的雲功能 - 有幾個承諾正在返回的功能結構
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({...