Node.js 节点js函数无法停止执行

Node.js 节点js函数无法停止执行,node.js,firebase,firebase-realtime-database,google-cloud-functions,Node.js,Firebase,Firebase Realtime Database,Google Cloud Functions,我为google cloud函数编写了这个node js函数,将firebase数据库节点条目索引到Algolia exports.indexlisting_algolia = functions.database.ref('/Listings/{listingId}') .onWrite((change, context) => { const index = algolia.initIndex('Listings'); const before = change

我为google cloud函数编写了这个node 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)));


}) 

函数可以工作,但它不会停止执行,它只是不断地重复自己。有什么问题,我如何解决这个问题?

通过执行
更改.after.ref.child('last\u index\u timestamp').set()
您正在写入云函数中正在侦听的引用。因此,云功能会自动触发自身

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

您很可能会使用
change.before.val()
和/或
change.after.val()
检查
last\u index\u timestamp
是否存在或是否具有特定值

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

有关此“技术”的示例,请参见以下官方示例(第30至32行)


最后(重要)一句话:您应该返回
set()
方法返回的承诺,并捕获潜在的错误,如下所示:

 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;
  });

我建议您观看以下官方视频系列“Firebase的学习云功能”(请参阅),特别是三个名为“学习JavaScript承诺”的视频,这解释了我们应该如何以及为什么在事件触发的云函数中链接和返回承诺。

在更改之前添加return.after会产生错误