【问题标题】:node js function could not stop executing节点js函数无法停止执行
【发布时间】:2018-09-07 18:18:46
【问题描述】:

我为谷歌云功能编写了这个节点 js 函数,以将 Firebase 数据库节点条目索引到 Algolia。

exports.indexlisting_algolia = 
 functions.database.ref('/Listings/{listingId}')
  .onWrite((change, context) => {
    const index = algolia.initIndex('Listings');
    const before = change.before;  // snapshot before the update
    const after = change.after;    // snapshot after the update
    const before_data = before.val();
    const after_data = after.val();
    after_data.objectID = context.params.listingId;
    console.log(Date.now());
            console.log(context)

return index.saveObject(after_data)

 .then(
  () => change.after.ref.child('last_index_timestamp').set(

     Date.parse(context.timestamp)));


}) 

该函数有效,但它不会停止执行,它只是一遍又一遍地重复自己。出了什么问题,我该如何解决?

【问题讨论】:

    标签: node.js firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    通过change.after.ref.child('last_index_timestamp').set(),您正在写入您在 Cloud Function 中收听的参考。所以云函数会自动触发。

    你应该在函数的开头检查它是否需要执行。

    您很可能会使用change.before.val() 和/或change.after.val() 来检查last_index_timestamp 是否存在或具有特定值。

    如果你想停止函数的执行,只需返回null

    有关此“技术”的示例,请参见以下官方示例(第 30 到 32 行)https://github.com/firebase/functions-samples/blob/952fe5d08c0a416f78def93fa337ca2bd73aedcf/message-translation/functions/index.js


    最后(重要)说明:您应该返回set() 方法返回的promise,并捕获潜在的错误,如下所示:

     return index.saveObject(after_data)
     .then(
      () => return change.after.ref.child('last_index_timestamp').set(Date.parse(context.timestamp))
     )
     .catch(err => {
        console.log('Error:', err);
        return false;
      });
    

    我建议您观看以下官方视频系列“Learning Cloud Functions for Firebase”(请参阅​​ https://firebase.google.com/docs/functions/video-series/),尤其是标题为“Learn JavaScript Promises”的三个视频,它们解释了我们应该如何以及为什么应该链接和在事件触发的 Cloud Functions 中返回 Promise。

    【讨论】:

    • 在change.after之前添加return会产生错误
    猜你喜欢
    • 1970-01-01
    • 2015-10-08
    • 2021-02-06
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 2022-01-23
    相关资源
    最近更新 更多