【问题标题】:Returning null from firebase cloud function - background triggers从 Firebase 云函数返回 null - 后台触发器
【发布时间】:2021-12-24 03:17:13
【问题描述】:

使用带有后台触发器的 firebase 云函数,如果没有处于待处理状态的承诺,Doug Stevenson 建议我们返回 null。以下是他建议的两个地方:

https://youtu.be/7IkUgCLr5oA?t=120

https://stackoverflow.com/a/52214464/188740

云函数中null有什么特殊处理吗?

例如,所有这些都应该正确终止:

export const onFooWrite = functions.firestore
  .document('foos/{fooId}')
  .onWrite((change, context) => {
    // do nothing (i.e. returns undefined)
  });


export const onFooWrite = functions.firestore
  .document('foos/{fooId}')
  .onWrite((change, context) => {
    return someAsyncFunction(); // returns a promise
  });

export const onFooWrite = functions.firestore
  .document('foos/{fooId}')
  .onWrite((change, context) => {
    if (something) return; // returns nothing (i.e. undefined)

    return someAsyncFunction(); // returns a promise
  });

export const onFooWrite = functions.firestore
  .document('foos/{fooId}')
  .onWrite(async (change, context) => {
    await someAsyncFunction();
    // returns nothing AFTER the promise is resolved
  });

我相信这些都很好,但 Doug Stevenson 建议在我们不返回承诺时返回 nullnull有特殊处理吗?

【问题讨论】:

  • T = 140s 在同一视频中 - “如果您返回任何其他类型的值(而不是 Promise),Cloud 函数将忽略它并终止该函数”。可能会返回一些对象,但由于它们是后台函数,它们不会被发送到任何地方,所以也许 null 似乎可以完成这项工作。
  • @Dharmaraj 并不意味着我们可以返回任何东西(不仅仅是null),它会是一样的吗?通过扩展,我们可以简单地不返回任何东西(这将被解释为返回undefined)并且应该做同样的事情,不是吗?所以换句话说,null没有什么特别的,对吧?还在寻找确认????

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


【解决方案1】:

我发现你肯定要听从Doug的建议,尽量回null,这也是why event-driven functions fail to complete的原因之一

当用 Node.js 编写的函数返回被拒绝的 Promise 或将非空值传递给回调时。

函数默认停止执行,事件被丢弃。

你还需要terminate your background functions并返回一个空值或者使用其他的promise方法。

如果函数创建后台任务(例如线程、期货、Node.js Promise 对象、回调或系统进程),您必须在从函数返回之前终止或以其他方式解决这些任务。在从特定执行返回之前未终止的任何任务可能无法完成,也可能导致未定义的行为。

【讨论】:

  • 宾果!你搞定了。您能否详细说明必须终止后台功能?我认为返回一个承诺就足够了,执行就会完成。
  • 访问提示和技巧页面,sectionthis。除此之外,我认为您应该更多地自行调查MDNW3 中的承诺,甚至快速上网搜索也有一些非常好的信息。
  • 我现在明白了。 terminating the background function 指的是后台任务(即从主函数调用的异步函数),而不是主函数本身。通常,主函数被称为监听器的后台函数(例如onCreateonWrite 等),所以只是术语混乱。
猜你喜欢
  • 1970-01-01
  • 2021-03-04
  • 2019-02-27
  • 1970-01-01
  • 2018-09-14
  • 2019-12-17
  • 2019-08-20
  • 2021-02-13
  • 1970-01-01
相关资源
最近更新 更多