【问题标题】:Function returned undefined, expected Promise or value. although i am returning snapshot.val();函数返回未定义的、预期的 Promise 或值。虽然我要返回 snapshot.val();
【发布时间】:2018-12-10 13:39:51
【问题描述】:

我正在为我的项目编写云函数。在过去的 12 个小时里,我一直遇到这个错误“函数返回未定义,预期的承诺或值” 我已经尝试了很多删除它但无法找到如何解决它

exports.Notify = functions.database.ref('blood_share/Notifications/{user}/{notificationid}').onWrite((change, context) => {

        const username=context.params.user;
        const notifyid=context.params.notificationid;


        const query = admin.database().ref("blood_share/Notifications").child(username).child(notifyid);
        query.once('value').then(snapshot=>{
         const event = snapshot.val();

        const notificationMessage = event.messsage;
        const token_id=event.reciever_appid;
        console.log("message"+notificationMessage);



        //create notification Json

        const payLoad = {
       notification:{
         title: "New Request For Food",
         body: "kuch b",
         icon: "default"
       }
     };

      return snapshot.val();

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

         });    

   });

【问题讨论】:

    标签: android firebase google-cloud-functions


    【解决方案1】:

    query.once('value') 承诺解决时,您将返回该值。

    为了澄清这一点,看看这个:

    let a = 0;
    asyncFunctionPromise.then(() => {
     a = 1;
    });
    console.log(a); // Will print 0 instead of 
    

    而不是直接返回承诺return query.once('value').then(.... 或构建你自己的

    return new Promise((resolve) => {
      query.once('value').then(snapshot=>{
           // do something
           resolve(snapshot.val()); // To resolve the promise with snapshot.val()
      });
    })
    

    【讨论】:

      【解决方案2】:

      你需要回报承诺

       return query.once('value').then(snapshot=>{
        //....
      

      【讨论】:

        【解决方案3】:

        返回一个Promise,而不是返回一个值的snapshot.val()

        return Promise.resolve(snapshot.val());
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-03-24
          • 1970-01-01
          • 1970-01-01
          • 2018-12-05
          • 2019-08-06
          • 2019-11-18
          • 2018-06-12
          • 2018-08-05
          相关资源
          最近更新 更多