【问题标题】:Firebase functions for loop async await用于循环异步等待的 Firebase 函数
【发布时间】:2019-06-02 14:35:32
【问题描述】:

我正在尝试使用 Firebase 函数做一个相对简单的理论上的函数。

具体来说:

  • + 1 添加到所有用户的实时数据库变量中

  • 向所有用户发送通知

我仍在努力理解async/await,这可能是我为此苦苦挣扎的原因。

这是我正在做的事情:

 exports.gcIncrement = functions.database
  .ref('gthreads/{threadId}/messages/{messageId}')
  .onCreate(async (snapshot, context) => {

    const data = snapshot.val();
    const threadId = context.params.threadId;
    const uid = context.auth.uid;
    
    adb.ref('gchats/' + threadId).once('value').then(async (gchatData) => {
    const parent = gchatData.val();
    incrementUser(parent.users, uid, threadId); //parent.users is an object with 1-30 users.
    sendGCNotification(parent.users, data);
    return true;
  }).catch(error => console.log(error))
});

然后我有函数incrementUser

function IncrementUser(array, uid, threadId) {
    for (const key in array) {
      if (key != uid) {
        const gcMessageRef =
        adb.ref('users/' + key + '/gthreads/' + threadId + '/' + threadId+'/unread/');
        gcMessageRef.transaction((int) => {
          return (int || 0) + 1;
      }
    }
  }

和函数sendGCNotification:

  function sendGCNotification(array, numbOfMsg, data) {
    let payload = {
      notification: {
        title: 'My App - ' + data.title,
        body: "This is a new notification!",
      }
    }
    const db = admin.firestore()
    for (const key in array) {
      if (!data.adminMessage) {
        if (array[key] === 0) {

          const devicesRef = db.collection('devices').where('userId', '==', key)

          const devices = await devicesRef.get();
          devices.forEach(result => {
            const tokens = [];
            const token = result.data().token;
            tokens.push(token)

            return admin.messaging().sendToDevice(tokens, payload)
          })

        }
      }
    }
  }
    

我目前收到错误:

'await' 表达式只允许在异步函数中使用。

const devices = await devicesRef.get();

但即使我得到它没有错误,它似乎也不起作用。 Firebase 函数日志说:

下午 4:45:26.207 gc增量 函数执行耗时 444 毫秒,完成状态为:'ok' 下午 4:45:25.763 gc增量 函数执行开始

所以它似乎按预期运行,但没有按预期完成代码。有任何想法吗?谢谢!

【问题讨论】:

    标签: javascript firebase google-cloud-functions


    【解决方案1】:

    await 的所有使用都必须在标记为 async 的函数的主体内发生。您的函数 sendGCNotification 不是异步的。您必须将其标记为异步,并确保其中的任何承诺都已等待,或者返回一个在所有异步工作完成后解析的承诺。

    另外,在IncrementUser 中,您没有处理 gcMessageRef.transaction() 返回的承诺。您需要处理从所有异步工作中生成的每一个 Promise,并确保它们都是您从顶级函数返回或等待的最终 Promise 的一部分。

    如果您想了解更多关于 Cloud Functions 代码中的 Promise 和 async/await 的信息,我建议您使用我的video series。具体来说,标题为“async/await 如何与 TypeScript 和 ECMAScript 2017 一起工作?”。即使你不使用 TypeScript,async/await 也一样。

    【讨论】:

      猜你喜欢
      • 2019-07-02
      • 1970-01-01
      • 2020-04-20
      • 2020-03-27
      • 2021-11-13
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      相关资源
      最近更新 更多