JavaScript函数返回值是firestore中未定义的快照

JavaScript函数返回值是firestore中未定义的快照,javascript,firebase,google-cloud-firestore,dialogflow-es,actions-on-google,Javascript,Firebase,Google Cloud Firestore,Dialogflow Es,Actions On Google,我有以下代码。函数caloriex的返回值始终未定义 当我在return语句之前显示返回的值时,它会显示正确的值。但是当它从函数返回时,它是未定义的。你能帮我解决这个问题吗 function caloriex(calorie, meal){ let citiesRef = db.collection('food'); let query = citiesRef.where('category_out', '==', calorie).where('category_in',

我有以下代码。函数caloriex的返回值始终未定义

当我在return语句之前显示返回的值时,它会显示正确的值。但是当它从函数返回时,它是未定义的。你能帮我解决这个问题吗

  function caloriex(calorie, meal){
    let citiesRef = db.collection('food');
    let query = citiesRef.where('category_out', '==', calorie).where('category_in', '==', meal).get()
      .then(snapshot => {
        if (snapshot.empty) {
          console.log('No matching documents.');
        }
        var workingbalance = '';
        snapshot.forEach(doc => {
          console.log(doc.id, '=>', doc.data());//this result is fine
          workingbalance = doc.data().id;
        });
        return workingbalance //returned VALUE is undefined 
      })
      .catch(err => {
        console.log('Error getting documents', err);
      });
  }

这是因为您从未从函数返回任何内容。它所做的就是让两个变量,然后有一堆来自内部函数的回调,这些回调不会影响外部函数的返回。语句return workingbalance只是从传递的内部lambda函数返回该值

如果您想有效地使用异步编程,就必须学习JavaScript中的承诺和承诺链是如何工作的。如果您想向调用者获取workingbalance值,最好返回整个承诺链,并让调用者使用该承诺获取值。因此,它将是

return citiesRef.where(...).then(...).catch(...)

您的函数正在返回[object promise],因为承诺未解析,您正在返回值。请使用wait调用Firestore函数。

您好,我试过了。但是,我得到了结果[object promise]。它应该是return citiesRef.where….get.then….catch。。。