0

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");
        });

    }

and next:

var warehouses = getWarehousesArray();

Unfortunately it doesn't work

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
awariat
  • 331
  • 1
  • 5
  • 22
  • What does "it doesn't work" mean? Is there an error? Does `warehouses` not contain what you expect it to contain? If so: please edit your question to show what you do with `warehouses` that is causing the problem. – Frank van Puffelen Jun 22 '19 at 14:36

2 Answers2

0

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.

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

var warehouses = await getWarehousesArray();

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
})
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

Thank you very much. The working function is:

async function myFunction() {
  var warehouses = await getWarehousesArray();
...
awariat
  • 331
  • 1
  • 5
  • 22