Skip to content Skip to sidebar Skip to footer

Firestore Query In Function 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 =

Solution 1:

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

Solution 2:

Thank you very much. The working function is:

async function myFunction() {
  var warehouses = await getWarehousesArray();
...

Post a Comment for "Firestore Query In Function Return"