首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Firebase数据库的云功能-- onWrite触发两次

Firebase数据库的云功能-- onWrite触发两次
EN

Stack Overflow用户
提问于 2017-03-31 02:32:59
回答 2查看 3.2K关注 0票数 4

嗨,我正在开发一个通知系统,但是我在删除处理后的通知数据时遇到了问题。onWrite事件侦听器被触发两次,导致两个通知。

你能帮我找个工作吗?这样onWrite事件侦听器就不会被触发两次?删除处理过的数据是很重要的。

代码语言:javascript
运行
复制
exports.sendMessageNotification = functions.database.ref('/notification/message/{recipientUid}/{senderUid}').onWrite(event => {
/* processing notification and sends FCM */

return admin.messaging().sendToDevice(tokens, payload).then(response => {
      // For each message check if there was an error.
      const toRemove = [];
      response.results.forEach((result, index) => {
        const error = result.error;
        if (error) {
          console.error('Failure sending notification to', tokens[index], error);
          // Cleanup the tokens who are not registered anymore.
          if (error.code === 'messaging/invalid-registration-token' ||
              error.code === 'messaging/registration-token-not-registered') {
            toRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
          }
        }
      });

      //Deletes processed notification
      console.log("Removing notification");
      const getNotificationPromise = admin.database().ref(`/notification/message/${recipientUid}/${senderUid}`).once('value');
      return Promise.all([getNotificationPromise]).then(results => {
        const notificationSnapshot = results[0];
        toRemove.push(notificationSnapshot.ref.remove());

        console.log("Removing tokens.")
        return Promise.all(toRemove);
      });
      //return Promise.all(tokensToRemove);
    });
});

})
EN

Stack Overflow用户

发布于 2017-08-18 20:47:19

如果有人仍对此感到困惑,as firebase-功能v0.5.9 ;您可以使用onCreate()、onUpdate()或onDelete()。

代码语言:javascript
运行
复制
npm install --save firebase-functions 

此外,firebase文档和示例中也提到,如果您使用的是onWrite(),正如道格前面所解释的那样,该函数将为该节点上的所有事件触发,即写入、更新或删除。因此,您应该检查,以确保您的函数不会卡在循环中。类似于:

代码语言:javascript
运行
复制
   //if data is not new 
    if (event.data.previous.exists()) {return}
    // Exit when the data is deleted; needed cuz after deleting the node this function runs once more.
    if (!event.data.exists()) {return}

干杯。

票数 3
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43131416

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档