用于 firebase 的云函数 - 返回多个承诺的函数结构

Cloud functions for firebase - Function structure with several promises being returned

需要知道我的功能是否结构良好并且 returning 承诺是否正确。我正在使用主要条件 if 语句处理新数据和已删除数据。如果数据存在,我正在执行一个数据库集并returning 一个承诺return ProposalsRef.child(recipient).set。如果数据不存在我returnreturn ProposalsRef.once('value')...。每当该函数被触发时,它只会 return 一个承诺(这样它就永远不会超时)。另外我在最后实现了一个 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 只 return contractRef... 承诺,contractRef 中的承诺是否也应该 returned(freelancerRef,clientRef)?如果是这样,我应该创建一个承诺数组然后 return Promise.all(arrayOfProimises); 还是我可以 return 单独 return freelancerRef.child("/notifications").push({...

Promise.all([...]) 将创建一个单一的承诺,只有在所有其他个人承诺都得到履行时才会履行。这是您应该从 then return(然后应该由整个函数 return 编辑)以确保它在清理之前等待所有工作完成。您将无法 return 单独承诺。