简体   繁体   中英

How to satisfy requirement to return promise in Firebase cloud function with nested conditions?

I've written a Firebase cloud function (below), which requires returning a promise to the caller. If the function doesn't meet a certain condition, must it return null or Promise.reject() , or something else? The function below (which is called from a mobile app) performs a Firestore read and sends an FCM message depending on the values within that read.

export const pushNotifyConnection = functions.https.onCall((data, _context) => {
    const recipientUserId = data.recipientUserId

    admin.firestore().collection("userSettings").doc(recipientUserId).get().then((snapshot) => {
        if (snapshot.exists) {
            const allowsConnectionNotifications = snapshot.get("private.connectionNotifications") || false

            if (allowsConnectionNotifications) {
                const fcmToken = snapshot.get("private.fcmToken")
                const message = {
                    ...
                }

                return admin.messaging().send(message)
            } else {
                return null // am I required to return this, Promise.reject(), or something else?
            }
        } else {
            return null // am I required to return this?
        }
    }).catch((error) => {
        return error // can I just return the error?
    })
})

Does this function satisfy the requirements of always returning a promise to properly terminate the function?

No, it does not. This function returns nothing from the top level function scope.

Minimally, you should return the promise chain started by admin.firestore().collection(...) . Optimally, the innermost return contains the object you want to send to the client. The data returned by admin.messaging().send(message) might not be what you actually want the client to receive.

In order to do this correctly, I strongly suggest seeking out some tutorials on how promises work. Also, it might be a good idea to start out with a simpler function that operates exactly as you expect (with no uncertainty), then gradually make it more complex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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