You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase Functions部署报错:Promises未正确处理及空块问题

Fixing Firebase Cloud Function Deployment Errors: Promises & Empty Block Issues

Hey there, let's work through why your function is failing on the new Firebase account—those two errors are pointing to unhandled asynchronous operations and minor code structure issues, which are super common when Firebase updates tighten up their Promise handling rules.

Let's Break Down the Errors

  • 'Promises must be handled appropriately': Firebase Cloud Functions require you to return promises for all asynchronous work so the runtime knows when your function is done. Right now, your code is returning a string (return "sadegh") before waiting for the Firestore get call and notification sends to finish. Also, your sendMessage function isn't returning the promise from admin.messaging().send(), leaving those operations unhandled.
  • 'block is empty': While your catch block does have code, the issue is likely tied to the incorrect promise chain—when the runtime doesn't see a properly resolved promise, it might flag empty-looking execution paths. Fixing the promise handling will resolve this too.

Here's the Fixed Code

I've adjusted the code to properly handle all promises, switched to async/await for cleaner readability, and ensured every asynchronous operation is tracked:

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();

export const sendChatNotification = functions
  .firestore.document('rooms/{roomId}/messages/{messageId}')
  .onCreate(async (snap, context) => { // Mark callback as async
    try {
      const roomId = context.params.roomId;
      const newValue = snap.data();
      const receiverId = newValue.receiverId;
      const text = newValue.text;
      const type = newValue.type;
      const senderName = newValue.senderName;

      // Await the Firestore get call instead of using .then()
      const snapshot2 = await admin.firestore().collection("users").doc(receiverId).get();
      const data2 = snapshot2.data();
      const firebaseNotificationToken = data2.firebaseNotificationToken;

      if (type === 'voiceCall' || type === 'videoCall' || type === 'hangUp') {
        const channelId = newValue.channelId;
        const senderId = newValue.senderId;
        const status = newValue.status;
        console.log(`type: ${type} /status: ${status}`);

        // Send data message
        const message = {
          data: {
            type: type,
            senderId: senderId,
            senderName: senderName,
            receiverId: receiverId,
            status: status,
            channelId: channelId,
            roomId: roomId
          },
          token: firebaseNotificationToken
        };
        await sendMessage(message); // Await the send operation

        if (status === "canceled") {
          const message1 = {
            notification: {
              title: '☎ Missed voice call ',
              body: senderName
            },
            token: firebaseNotificationToken
          };
          await sendMessage(message1);
        } else if ((type === 'voiceCall' || type === 'videoCall') && status === '') {
          const message1 = {
            notification: {
              title: `☎ ${senderName} is calling you`,
              body: 'tap to answer...'
            },
            token: firebaseNotificationToken
          };
          await sendMessage(message1);
        }
      } else {
        const message = {
          notification: {
            title: `📃 ${senderName}`,
            body: text
          },
          token: firebaseNotificationToken
        };
        await sendMessage(message);
      }

      return null; // Indicate successful completion
    } catch (e) {
      console.log('error: ' + e);
      return null; // Handle errors properly
    }
  });

// Modified to return the promise so we can await it
async function sendMessage(message) {
  try {
    const response = await admin.messaging().send(message);
    console.log('Successfully sent message:', response);
    return response;
  } catch (error) {
    console.log('Error sending message:', error);
    throw error; // Re-throw so the caller can handle the error
  }
}

Key Changes Made

  1. Async/Await for Readability: Switched from .then() chains to async/await to make the flow easier to follow and ensure all promises are awaited.
  2. Return Promises Everywhere: The sendMessage function now returns the promise from admin.messaging().send(), and we await it in the main function so Firebase waits for notifications to send.
  3. Proper Function Return: The main onCreate function now returns after all async work is done, and we use a try/catch block to handle errors consistently.
  4. No Early Returns: Removed the stray return "sadegh" that was causing the runtime to exit before async operations finished.

These changes should resolve both deployment errors—Firebase will now properly track all asynchronous work, and there won't be any "empty block" issues because every code path has a clear return or error handling.

内容的提问来源于stack exchange,提问作者Sadegh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:09:07