【问题标题】:How to only get one value of child firebase cloud function?如何仅获取子 Firebase 云功能的一个值?
【发布时间】:2019-02-22 06:07:53
【问题描述】:

我想发送触发到 pengumuman 主题的通知。

export const onNotifPengumuman = functions.database.ref('/pengumuman_course/{course_id_p}/{pengumuman_id}')
.onCreate((snapshot,context) =>{


    const course_id_p = context.params.course_id_p;
    const pengumuman_id = context.params.pengumuman_id;



    const nama_matkul = admin.database().ref('/courses/'+course_id_p+'name').once('value').then(snap =>{

        return snapshot.val();

        }).catch(error =>
             {
        console.log(error);
    })

    console.log(`cobacobacoba ${nama_matkul}`);

    return admin.database().ref('pengumuman/' + pengumuman_id + '/').once('value').then(snap =>{
        const pengumumanData = snap.val();
        const notifDataPengumuman = {
            data:{
                data_type: "pengumuman ",
                title: "Pengumuman Baru", // data bebas (key, value)
                body: `${nama_matkul}`, // chatId = const chatId
                sound: "default"
            }
        }
        return admin.messaging().sendToTopic(course_id_p, notifDataPengumuman) 

            .then(function(response) {
                console.log("Successfully sent message:", response);
              })
            .catch(function(error) {
                console.log("Error sending message:", error);
              });


    }).catch(error => {
        console.log(error);
    })

});

在第一个参考functions.database.ref('/pengumuman_course/{course_id_p}/{pengumuman_id}')我想在firebase实时数据库中访问和触发这个孩子,下面的代码:

enter image description here

在此代码return admin.database().ref('pengumuman/' + pengumuman_id + '/') 之后,我试图获取有关 pengumuman 的所有信息并将其发送给用户。下面的代码: enter image description here

但在此之前,我想在数据库中的课程引用中获取 pengumuman 名称以获取名称的值,使用以下代码:

 const nama_matkul = admin.database().ref('/courses/'+course_id_p+'name').once('value').then(snap =>{

        return snapshot.val();

        }).catch(error =>
             {
        console.log(error);
    })

enter image description here

问题是当我使用该代码获取子名称并将其存储到 matkul 中时,当我发送/记录时,它将返回承诺对象。我想要显示“REKAYASA PERANGKAT LUNAK”的结果。 谢谢,抱歉解释不好

[已修复]

我正在尝试解决方案并找到此代码

export const onNotifPengumuman = functions.database.ref('/pengumuman_course/{course_id_p}/{pengumuman_id}')
.onCreate((snapshot,context) =>{


    const course_id_p = context.params.course_id_p;
    console.log(`course id pengumuman ${course_id_p}`);
    const pengumuman_id = context.params.pengumuman_id;

    admin.database().ref('/courses/' + course_id_p + '/').once('value').then(snap2 =>{
        const nama_matkul = snap2.child('name').val();

        console.log(`nama matkul dari sini ${nama_matkul}`);

        admin.database().ref('pengumuman/' + pengumuman_id + '/').once('value').then(snap =>{
            const pengumumanData = snap.val();
            const notifDataPengumuman = {
                data:{
                    data_type: "pengumuman",
                    title: "Pengumuman Baru", // data bebas (key, value)
                    body: `Judul :${nama_matkul}`, // chatId = const chatId
                    sound: "default"
                }
            }
            return admin.messaging().sendToTopic(course_id_p, notifDataPengumuman) 

                .then(function(response) {
                    console.log("Successfully sent message:", response);
                  })
                .catch(function(error) {
                    console.log("Error sending message:", error);
                  });


        }).catch(error => {
            console.log(error);
        })
    }).catch(error =>{
        console.log(error);
    })



});

【问题讨论】:

  • 试试ref('/courses/{courseId}/name')

标签: node.js firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions


【解决方案1】:

您需要解析 Promise 才能获得它们返回的值。您目前正在做的是分配 nama_matkul 承诺,但您从不等待它完成。

异步/等待
您可以通过将函数定义为异步来使用async/await

.onCreate(async (snapshot,context) =>{
  // Your asynchronous code here
}

然后您可以通过运行来解决承诺 const nama_matkul = (await admin.database().ref('/courses/'+course_id_p+'name').once('value')).val();

如果您需要处理异常,请将 promise 包装起来并在 try catch 块中等待。

重构代码后,它可能看起来像这样:

export const onNotifPengumuman = functions.database.ref('/pengumuman_course/{course_id_p}/{pengumuman_id}')
.onCreate(async (snapshot,context) => {
  try {
    const course_id_p = context.params.course_id_p;
    const pengumuman_id = context.params.pengumuman_id;
    const nama_matkul = (await admin.database().ref('/courses/'+course_id_p+'name').once('value')).val();
    console.log(`cobacobacoba ${nama_matkul}`);

    const pengumumanData = (await admin.database().ref('pengumuman/' + pengumuman_id + '/').once('value')).val();
    const notifDataPengumuman = {
        data: {
            data_type: "pengumuman ",
            title: "Pengumuman Baru", // data bebas (key, value)
            body: `${nama_matkul}`, // chatId = const chatId
            sound: "default"
        }
    }
    try {
      await admin.messaging().sendToTopic(course_id_p, notifDataPengumuman);
      console.log("Successfully sent message:", response);
    } catch (messageSendError) {
      console.log("Error sending message:", messageSendError);
    } 
  } catch (error) {
    console.log(error);
  }

});

然后/赶上

如果您确实想坚持当前的设置并使用回调,则可以改为保留 .then 调用并在回调中处理您的应用程序逻辑;您的代码可能如下所示:

export const onNotifPengumuman = functions.database.ref('/pengumuman_course/{course_id_p}/{pengumuman_id}')
.onCreate((snapshot,context) => {
    const course_id_p = context.params.course_id_p;
    const pengumuman_id = context.params.pengumuman_id;
    admin.database().ref('/courses/'+course_id_p+'name').once('value')
      .then(nameSnapshot => {
        const nama_matkul = nameSnapshot.val();

        console.log(`cobacobacoba ${nama_matkul}`);
        admin.database().ref('pengumuman/' + pengumuman_id + '/').once('value')
          .then(dataSnapshot => {
            const pengumumanData = dataSnapshot.val();
            const notifDataPengumuman = {
                data: {
                    data_type: "pengumuman ",
                    title: "Pengumuman Baru", // data bebas (key, value)
                    body: `${nama_matkul}`, // chatId = const chatId
                    sound: "default"
                }
            }
            return admin.messaging().sendToTopic(course_id_p, notifDataPengumuman)
              .then(response => console.log("Successfully sent message:", response))
              .catch(error => console.log("Error sending message:", error));
          })
          .catch(error => console.log(error));
      })
      .catch(error => console.log(error))


});

如果您愿意,当然可以使用 then/catch 和 await 的组合,这是否是一种好习惯或何时使用,这实际上取决于您使用它的情况。

【讨论】:

  • 先生,我正在尝试遵循您的第二个选项。但 nama_matkul 为空。会发生什么?
  • 嘿,我已经解决了我的代码中的问题。我错误地命名了其中的两个变量。请注意.then(nameSnapshot => { 行和const nama_matkul = nameSnapshot.val(); 行。我希望这会有所帮助。
猜你喜欢
  • 2019-10-17
  • 1970-01-01
  • 2017-09-15
  • 2019-01-24
  • 2017-10-14
  • 2020-02-28
  • 1970-01-01
  • 2020-03-03
  • 2019-08-08
相关资源
最近更新 更多