【问题标题】:How to run asynchronous code in Cloud Firestore triggers如何在 Cloud Firestore 触发器中运行异步代码
【发布时间】:2021-01-13 13:13:24
【问题描述】:

我正在使用此处记录的 Cloud Firestore 触发器。 https://firebase.google.com/docs/functions/firestore-events

如何从这些函数之一运行异步代码?这是我想做的一个例子。

async function doSomething(data) {
   // ...
}

exports.updateUser = functions.firestore
    .document('users/{userId}')
    .onUpdate((change, context) => {
       await doSomething(change.after.data());
});

当我尝试部署此功能时,我收到此错误消息。

return await doSomething(change.after.data());
       ^^^^^

SyntaxError: await is only valid in async function

【问题讨论】:

    标签: javascript firebase google-cloud-firestore async-await


    【解决方案1】:

    如果要使用await 调用async 函数,则还必须声明封闭函数async

    exports.updateUser = functions.firestore
        .document('users/{userId}')
        .onUpdate(async (change, context) => {
           await doSomething(change.after.data());
    });
    

    请注意我将async 放在第三行的位置。此语法并非 Cloud Functions 独有 - 这是标准 JavaScript。

    【讨论】:

      猜你喜欢
      • 2018-03-27
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      • 2015-12-05
      • 2011-08-19
      • 2020-02-04
      • 1970-01-01
      • 2018-03-27
      相关资源
      最近更新 更多