为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用类型脚本中的函数从火库获取文档?

如何使用类型脚本中的函数从火库获取文档?

偶然的你 2022-09-23 16:39:09
我想使用用户的 ID 从我的集合中获取用户信息,以便向他们发送通知。这是我在索引.ts中的函数export const sendNotifications = functions.firestore.document('messages/{groupId1}/{groupId2}/{message}').onCreate((snapshot, context) =>{    console.log('Starting sendNotification Function');       const doc = snapshot.data();    console.log(doc.content);    console.log(getUserData(doc.idFrom))    return true;});export async function getUserData(id: string){    try {        const snapshot = await admin.firestore().collection('users').doc(id).get();        const userData = snapshot.data();        if(userData){            return userData.nickname;        }           } catch (error) {                console.log('Error getting User Information:', error);        return `NOT FOUND: ${error}`    } }从我的部署中,我收到控制台日志消息,“启动发送通知函数”,然后是实际的“doc.content”,然后是我的“getUserData(doc.idFrom)”的错误。Promise {  <pending>,  domain:    Domain {     domain: null,     _events: { error: [Function] },     _eventsCount: 1,     _maxListeners: undefined,     members: [] } } 提前感谢您!
查看完整描述

1 回答

?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

应使用 调用异步函数。getUserData()await


以下应该可以解决问题(未经测试):


export const sendNotifications = functions.firestore

  .document('messages/{groupId1}/{groupId2}/{message}')

  .onCreate(async (snapshot, context) => {

    try {

      console.log('Starting sendNotification Function');

      const doc = snapshot.data();

      console.log(doc.content);


      const nickname = await getUserData(doc.idFrom);

      // Do something with the nickname value

      return true;

    } catch (error) {

      // ...

    }

  });


async function getUserData(id: string) {

  try {

    const snapshot = await admin.firestore().collection('users').doc(id).get();

    if (snapshot.exists) {

       const userData = snapshot.data();

       return userData.nickname;

    } else {

      //Throw an error

    }

  } catch (error) {

    // I would suggest you throw an error

    console.log('Error getting User Information:', error);

    return `NOT FOUND: ${error}`;

  }

}

或者,如果您不想使用云功能异步,可以执行以下操作:


export const sendNotifications = functions.firestore

  .document('messages/{groupId1}/{groupId2}/{message}')

  .onCreate((snapshot, context) => {

    console.log('Starting sendNotification Function');

    const doc = snapshot.data();

    console.log(doc.content);


    return getUserData(doc.idFrom)

      .then((nickname) => {

        // Do something with the nickname value

        return true;

      })

      .catch((error) => {

        console.log(error);

        return true;

      });

  });


查看完整回答
反对 回复 2022-09-23
  • 1 回答
  • 0 关注
  • 85 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信