函数返回中的Firestore查询 [英] Firestore query in function return

查看:38
本文介绍了函数返回中的Firestore查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Firestore中有一个数组,我想在许多地方使用它.对我而言,最好的方法是使用return这样的函数:

I have array in Firestore which I would like to use in many places. The best for me would be to have function with return like this:

function getWarehousesArray() {


    let db = firebase.firestore();
      var user = db.collection("users").doc(firebase.auth().currentUser.email);
      var warehousesArray = new Array();
      return user.get()
        .then(function (doc) {
          if (doc.exists) {

            warehousesArray = doc.data().warehouses_array;
            return warehousesArray

          } else {
            swal("Error!", "No such document!", "error");
          }
          //return warehousesArray
        }).catch(function (error) {
          swal("Error!", error, "error");
        });

    }

然后下一个:

var warehouses = getWarehousesArray();

不幸的是,它不起作用

推荐答案

由于Firestore中的数据可能需要来自服务器,因此它是异步加载的.您从 getWarehousesArray 返回的值不是实际的仓库数组(因为在 return user ... 运行时尚不可用),而是一个<这些值的代码>承诺.

Since data from Firestore may need to come from the server, it is loaded asynchronously. The value you return from getWarehousesArray is not the actual array of warehouses (since that won't be available yet by the time return user... runs), but a Promise of those values.

要获取仓库的实际清单,可以使用 async / await (如果您定位的是现代JavaScript):

To get the actual list of warehouses you can either use async/await (if you're targeting modern JavaScript):

var warehouses = await getWarehousesArray();

您需要将包含此代码的函数标记为 async ,如此

You'll need to mark the function that contains this code as async, as shown in this MDN article on async/await.

或者,对于较旧的环境,您可以取消承诺:

Alternatively for older environments, you can just unwrap the promise:

getWarehousesArray().then(function(warehouses) {
    console.log(warehouses);
    ... anything that uses warehouses needs to be inside this callback
})

这篇关于函数返回中的Firestore查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆