Firebase Cloud Function错误,函数返回undefined,预期Promise或value

问题描述 投票:1回答:1

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

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个回答
0
投票

我会修改你的代码如下。请参阅代码中的注释。

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;
© www.soinside.com 2019 - 2024. All rights reserved.