繁体   English   中英

firebase 云 function 对文档执行多项操作时如何正确使用'return'

[英]How to properly use 'return' in a firebase cloud function when performing multiple actions against documents

我试图了解如何正确使用云 function..

a 下面的云 function 达到了预期的结果,但是,我没有在其中使用“返回”。

这是一个问题吗? 如果是,我该如何解决?

exports.onJobChangeToClosedAndSubstateIsCancelled = functions.firestore
    .document("job/{docId}")
    .onUpdate(async (change, eventContext) => {
        const afterSnapData = change.after.data();
        const afterJobState = afterSnapData["Job state"];
        const afterJobSubState = afterSnapData["Job substate"];

        if (afterJobSubState == "Cancelled" && afterJobState == "Closed") {

            // get all job related job applications
            const relatedJobApplicationsList = await admin.firestore().collection("job application").where("Job id", "==", change.before.id).get();
            // mark job applications closed so that other contractors cant waste their time
            relatedJobApplicationsList.forEach(async doc => {

                await admin.firestore().collection("job application").doc(doc.id).update({
                    "Job application state": "Closed",
                    "Job application substate": "Job cancelled by client",
                })

            })


        }
    });

我从其他问题(例如下面的问题)中的理解是,我应该返回对文档的更改或正在发生的操作。 (这是正确的吗?) 你能帮我吗?-firebase-function-onUpdate

下面是云 function 的示例,我可以在其中放置“return”语句:

// when a chat message is created
// send a notification to the user who is on the other side of the chat
// update the chat 'Chat last update' so that the Chats screen can put the chat at the top of the page
exports.onChatMessageCreate = functions.firestore
    .document("chat messages/{docId}")
    .onCreate(async (snapshot, context) => {
        const snapData = snapshot.data();
        // information about who sent the message
        const senderUserName = snapData["Chat message creator first name"];
        const senderUserId = snapData["User id"];
        // chat id to which chat messages belong to
        const chatId = snapData["Chat id"];

        // information about who should receive the message
        let receiverUserId;
        let receiverToken = "";

        // fetch user to send message to
        const chatData = await (await admin.firestore().collection("chat").doc(chatId).get()).data();
        const chatUsersData = chatData["User ids list"];

        chatUsersData[0] == senderUserId ? receiverUserId = chatUsersData[1] : receiverUserId = chatUsersData[0];

        receiverToken = await (await admin.firestore().collection("user token").doc(receiverUserId).get()).data()["token"];

        console.log("admin.firestore.FieldValue.serverTimestamp()::   " + admin.firestore.FieldValue.serverTimestamp());

        // set chat last update
        await admin.firestore().collection("chat").doc(chatId).update({
            "Chat last update": admin.firestore.FieldValue.serverTimestamp(),
        });

        const payload = {
            notification: {
                title: senderUserName,
                body: snapData["Chat message"],
                sound: "default",
            },
            data: {
                click_action: "FLUTTER_NOTIFICATION_CLICK",
                message: "Sample Push Message",
            },
        };

        return await admin.messaging().sendToDevice(receiverToken, payload);
    });

这是一个问题吗?

是的,如果不返回 Promise(或一个值,因为您的回调 function 是async的),您就错误地管理了 Cloud Function 的生命周期。

在您的情况下,由于您有一个 if 块,最简单的方法就是return null; (或return 0;return; )在 CF 的末尾,如下所示。

此外,您需要使用Promise.all() ,因为您希望并行执行对异步方法的可变数量的调用。

exports.onJobChangeToClosedAndSubstateIsCancelled = functions.firestore
    .document("job/{docId}")
    .onUpdate(async (change, eventContext) => {
        const afterSnapData = change.after.data();
        const afterJobState = afterSnapData["Job state"];
        const afterJobSubState = afterSnapData["Job substate"];

        if (afterJobSubState == "Cancelled" && afterJobState == "Closed") {

            // get all job related job applications
            const relatedJobApplicationsList = await admin.firestore().collection("job application").where("Job id", "==", change.before.id).get();
            
            // mark job applications closed so that other contractors cant waste their time
            const promises = [];

            relatedJobApplicationsList.forEach(doc => {

                promises.push(admin.firestore().collection("job application").doc(doc.id).update({
                    "Job application state": "Closed",
                    "Job application substate": "Job cancelled by client",
                }));

            })

            await Promise.all(promises);
        }
        
        return null;
    });

文档中有关如何正确管理 CF 生命周期 更多信息。

您可能还会对我在 2021 年I/O Extended UK & Ireland 活动的演讲感兴趣。这次演讲专门针对这个主题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM