【问题标题】:Firebase Cloud Function error, Function returned undefined, expected Promise or valueFirebase 云函数错误,函数返回未定义,预期的 Promise 或值
【发布时间】:2019-08-12 03:31:13
【问题描述】:

我有一个在某些数据库写入(onCreate)上触发的云函数,它按预期工作,但它也抛出一个错误“函数返回未定义,预期的承诺或值”,尽管我正在返回一个承诺。 附上下面的代码sn-p。其中有嵌套的承诺。有没有更好的方法来处理嵌套的 Promise,我已经检查了很多帖子中的嵌套 Promise,但无法找到合适的解决方案。 提前致谢

exports.calculateAnswer = function(snap, context, dbPath,bucket) {
  const answerKey = snap.val();
  const incidentId = context.params.incidentId;
  const matchId = context.params.match;
  var globalIncidentPath = globalIncidentRootPath.replace('${match}', matchId);
  globalIncidentPath = globalIncidentPath + incidentId + '/'

  var pdPath =  pdRootPath.replace('${match}', matchId);
  pdPath = pdPath + incidentId
   pdPath = pdPath + "/" + bucket
  var incidentsPath = incidentsRootPath.replace('${match}', matchId);
  var earningsNodePath = earningsNodeRootPath.replace('${match}', matchId);
  let app = admin.app();
  var globalData = null;
      var globalData = null;
      const globalPromise = app.database(dbPath).ref(globalIncidentPath).once('value').then(function(snapshot) {
              globalData = snapshot.val();
              console.log("globalData ",globalIncidentPath, "data ",globalData);
              if(globalData) {
                console.log("fetching pddata")
                 return app.database(dbPath).ref(pdPath).once('value')
                }
                else{
                  console.log("No global data found");
                  return true
                }
      }).then(function(pdSnashot){
            const pdData = pdSnashot.val()
        if(pdData) {
          var promises = []
          pdSnashot.forEach(function(childSnap){
            console.log('key ',childSnap.key)
            console.log('users count ',childSnap.numChildren())
              childSnap.forEach(function(usersSnap){
              const userId = usersSnap.key
              const incidentProcessed = incidentsPath + userId + '/processed/' + incidentId
              if (childSnap.key === answerKey) {
                    const earningUserIdEPath = earningsNodePath + userId
                    //const earningEPath = earningUserIdEPath + '/e/'
                    let gocashValue = globalData['v'];

                    const earningFetchPromise = app.database(dbPath).ref(earningUserIdEPath).once('value').then(function(snapshot1){
                      let snapDict = snapshot1.val();
                      var newGoCash = gocashValue
                      var newPDGoCash = gocashValue
                      if (snapDict){
                        let currentGoCash =snapDict['e'];
                        let currentPDCash = snapDict['pd']
                        if(currentGoCash) {
                          newGoCash = currentGoCash + gocashValue;
                        }
                        if(currentPDCash) {
                          newPDGoCash = currentPDCash + gocashValue;
                        }
                      }
                      const obj = Object()
                      obj["e"] = newGoCash
                      obj["pd"] = newPDGoCash

                      const earningPromise = app.database(dbPath).ref(earningUserIdEPath).update(obj)
                      const tempGlobal = globalData
                      tempGlobal["skip"] = false;
                      const processedPromise = app.database(dbPath).ref(incidentProcessed).set(tempGlobal)
                      return Promise.all([earningPromise,processedPromise])
                    });
                    promises.push(earningFetchPromise)
                  }
                  else{
                    const tempGlobal = globalData
                    tempGlobal["skip"] = true;
                    const processIncidentPromise = app.database(dbPath).ref(incidentProcessed).set(tempGlobal);
                    promises.push(processIncidentPromise)
                  }
            })
          })
          return Promise.all(promises).then(value => {
                console.log("Pd promises completed",value);
                return true
          })
        }
        else{
          console.log("No Pd Data Found");
          return true
        }
      })
      .catch(function(error){
            console.log('error in promise resolve',error)
      })
      console.log('global promise',globalPromise)
      return Promise.all([globalPromise])
     })

【问题讨论】:

  • 请编辑问题以显示整个函数,而不仅仅是部分代码。我很难弄清楚你的代码想要完成什么。
  • 您确定这与云功能有关,正如主题所暗示的那样?我在任何地方都没有看到云函数定义。
  • 是的,这是云功能,还添加了初始代码行

标签: javascript node.js firebase firebase-realtime-database firebase-admin


【解决方案1】:

我会修改你的代码如下。查看代码中的 cmets。

var globalData = null;
const globalPromise = app
  .database(dbPath)
  .ref(globalIncidentPath)
  .once('value')
  .then(function(snapshot) {
    globalData = snapshot.val();
    console.log('globalData ', globalIncidentPath, 'data ', globalData);
    if (globalData) {
      console.log('fetching pddata');
      return app
        .database(dbPath)
        .ref(pdPath)
        .once('value');
    } else {
      console.log('No global data found');
      // return true;   Better to throw an error here
      throw new Error('No global data found');
    }
  })
  //The following 3 lines don't bring anything
  //Moreover they are most probably the reason of your error as you don't return anything in this then()
  //.then(function(pdSnashot){   
  //   console.log("");
  //})
  .catch(function(error) {
    console.log('error in promise resolve', error);
    return true;
    //Note that if you don't need the console.log you may ommit the entire catch since the platform will handle the error itself.
  });

console.log('global promise', globalPromise);
//return Promise.all([globalPromise]); // There is no reason to use Promise.all() here since there is only one promise chain returned in globalPromise
return globalPromise;

【讨论】:

  • Cloud Function 日志中出现哪个错误?另外,你能分享一下你的Cloud Function的整个代码,而不仅仅是globalPromise的定义吗?
  • 该函数工作正常但仍然,它说“函数返回未定义,预期的承诺或值”
猜你喜欢
  • 2018-12-03
  • 1970-01-01
  • 2018-06-12
  • 2019-08-06
  • 2019-11-03
  • 2018-12-05
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多