【问题标题】:Why my cloud function is not executing for all my entries为什么我的所有条目都没有执行我的云功能
【发布时间】:2020-07-24 22:24:09
【问题描述】:

我有一个功能可以遍历我的订单类别中的每个订单,让用户的订单早于 1 天,并向他们发送提醒通知,但由于某种原因,当我执行此调用时,有时会发送通知,有时会发送通知不是,为什么会这样?

exports.sendReminder = functions.https.onRequest(async (req, res) => {
    const db = admin.firestore();
    const messaging = admin.messaging();

    const tsToMillis = admin.firestore.Timestamp.now().toMillis()
    const compareDate = new Date(tsToMillis - (24 * 60 * 60 * 1000))
    
    const snap = await db.collection('orders').where("timestamp","<",new Date(compareDate)).where("status", "in" ,[1,2,4,5,6]).get()
    let allPromises = [];

    if(snap.size > 0){
        snap.forEach((doc) => {
            const userId = doc.data().uid;

            allPromises.push(db.collection('user').doc(userId).get().then(userSnapshot => {
                const userData = userSnapshot.data();
                if (userData) {
                    const deviceToken = userData.deviceToken;
                    const payload = {
                        notification: {
                            title: "¿ Did you receive your order ?",
                            body: "We would love to know if you have received your order",
                            clickAction: "AppMainActivity"
                        },
                        data: {
                            ORDER_REMINDER: "ORDER_REMINDER"
                        }
                    }
                    res.status(200).send('Done!')
                    return messaging.sendToDevice(deviceToken,payload) 
                } else {
                    return null;
                }
            }));
        }); 
    }
    return Promise.all(allPromises);
});

为什么这个功能不能正确发送通知?我之前遇到过 Firebase 云功能的这个问题,它似乎没有正确处理通知的传播,我做错了什么?

【问题讨论】:

    标签: javascript firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    您在发送推送通知之前发送响应。只要您在云函数中使用res.send(),就会认为执行完成,CPU/网络资源将被限制。你可能想要这个:

    return messaging.sendToDevice(deviceToken,payload).then(() => {
      res.status(200).send('Done!')
    });
    

    【讨论】:

    • 嗨迈克尔,因为这不是我执行的最后一个承诺,所以它说每个人都应该返回或抛出异常
    【解决方案2】:

    由于迈克尔提到的原因,您需要延迟发送响应,直到所有消息都发送完毕。将send() 退出循环并使其成为最后一件事:

    Promise.all(allPromises).then(() => {
      res.status(200).send('Done!')
      return null;
    });
    return null;
    

    【讨论】:

    • 这应该在我的功能结束时?因为它还期望每个 then 都应该返回异常或抛出
    • 如果您的 lint 工具需要,您可以在 promise 回调的底部添加一个 return。它可能不希望您“返回异常”。
    • 当我们在 Promise 中返回 null 时,它表示它完成了 Promise 中每个 Promise 的所有工作。好吗?
    • 我收到了这个错误 doug 错误:无法处理请求
    • 这听起来像是一个全新的、完全不同的问题。发布一个新问题,以解释现在没有按您预期的方式工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    • 1970-01-01
    • 2013-09-08
    • 2022-01-20
    • 2020-08-22
    • 1970-01-01
    相关资源
    最近更新 更多