VUE和FIREBASE问题:错误:函数从请求范围函数调用中崩溃了



我看过这个问题,但没有好的答案。我可以理解问题是什么,但似乎无法找到如何解决问题。这是我的功能:

//set JSON content type and CORS headers for the response
response.header('Content-Type','application/json');
response.header('Access-Control-Allow-Origin', '*');
response.header('Access-Control-Allow-Headers', '*');
//respond to CORS preflight requests
if (request.method == 'OPTIONS') {
response.status(204).send('');
}
// pull in firebase
var firebase = require('firebase');
require("firebase/firestore");
let config = {
  // config stuff here
}
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
// grab doc id from request
var id = request.query.docId;
// declare connection to firestore
var db = firebase.firestore();
// grab user from request
var docRef = db.collection("clients").doc(id);
// grab the users server and id
docRef.get().then(function(doc) {
// grab the account id
var accountId = doc.data().accountId;
// declare master variable that will be returned
var toReturn = [];
// declare variables that will be returned in toReturn
var gpmGames = [];
var cspmGames = [];
var damageGames = [];
var damageToChampionsGames = [];
var damageTakenGames = [];
var wardsGames = [];
db.collection('games')
  .where('accountId', '==', accountId)
  .get()
  .then((res) => {
    var games = res.docs;
    // iterate through games and get averages and totals to return
    games.forEach(function(game) {
      gpmGames.push(game.data().gpm);
      cspmGames.push(game.data().cspm);
      damageGames.push(game.data().damage);
      damageToChampionsGames.push(game.data().damagetochampions);
      damageTakenGames.push(game.data().damagerecieved);
      wardsGames.push(game.data().wards);
    });
  });
  toReturn['gpmGames'] = gpmGames;
  toReturn['cspmGames'] = cspmGames;
  toReturn['damageGames'] = damageGames;
  toReturn['damageToChampionsGames'] = damageToChampionsGames;
  toReturn['damageTakenGames'] = damageTakenGames;
  toReturn['wardsGames'] = wardsGames;
response.status(200).send(toReturn);
});

因此,我知道在运行所有操作之前,我的返回都会被调用。我该如何解决?当然,我的返回给了一个空数组,我从firebase那里得到错误:错误:函数从请求范围函数调用中断出来。

谢谢!

您必须使用从中返回的承诺:

db.collection('games')
  .where('accountId', '==', accountId)
  .get()

这是一个异步电话,它立即以工作完成后解决的诺言返回。

您需要使用该承诺在正确的时间发送响应:

const proimise = db.collection('games')
  .where('accountId', '==', accountId)
  .get()
promise.then(snapshot => {
    // work with the document snapshot here, and send your response
})
.catch(error => {
    // deal with any errors if necessary.
    response.status(500).send(error)
})

您发送响应的方式似乎还可以,您只需要等到获取完成。

最新更新