Cloud Function 完成状态:'timeout',同时向 Firestore 添加数据

Cloud Function finished with status: 'timeout' while adding data to Firestore

这是代码,

exports.onEmailRecieved = functions.database
  .ref("/emails/recieved/{id}/")
  .onCreate(async (snapshot, context) => {
    const email = snapshot.val();
    const id = context.params.id;

    const trimmedEmailBody = String(email.body).replace("\n", "").trim();

    if (trimmedEmailBody === cmd) {
      const queueRef = fs.collection("requests").doc("all").collection("queue");

      await fs
        .runTransaction(async (t) => {
          const doc = await t.get(queueRef);
          const size = doc.size;

          console.log(`Size: ${size}`);

          console.log("Adding to queue.");

          await queueRef
            .add({
              email: email.email,
              subject: email.subject,
              body: email.body,
            })
            .then(() => {
              console.log("Successfully added to queue.");
            })
            .catch((err) => {
              console.log(err);
            })
            .finally(() => {
              console.log("It's finally over.");
            });

          return console.log("Worked?");
        })
        .then(() => {
          return console.log("Complete");
        })
        .catch((err) => {
          return console.log(err);
        });

      return console.log("Worked I guess.");
    } else {
      return console.log("Not equal.");
    }
  });

别在意那帮没用的console.logs。添加 em 以调试错误。

首先 console.log 被调用,然后什么都没有,没有 thencatchfinally 函数被触发,我得到一个函数完成状态:'timeout' 日志中的消息。

我做错了什么?

add() 方法 return 是一个承诺,然后当您等待承诺时,函数会以 non-blocking 的方式暂停,直到承诺完成。它将等待交易完成,然后再解决文档的创建,这会导致云功能超时,默认情况下为 1 分钟。通过删除 add 方法上的 await ,您将改为执行该函数。请参阅下面的代码:

messageRef
.add({
  email: "email",
  subject: "subj",
  body: "body",
})
.then(() => {
  console.log("Successfully added to queue.");
})
.catch((err) => {
  console.log(err);
})
.finally(() => {
  console.log("It's finally over.");
});

现在 return 是这样的:

Size: 1
Adding to queue.
test
Successfully added to queue.
It's finally over.

更多相关信息,您可以查看此文档: