亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用類型腳本中的函數從火庫獲取文檔?

如何使用類型腳本中的函數從火庫獲取文檔?

偶然的你 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 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號