0

What I'm trying to do

I'm still new to working with asynchronous code, I'm trying to do something basic, but I'm not seeing what's missing here.

So I have this function that gets all orders from Firestore.

getAllOrders() = async () => {
    var orderArray = []

    this.firestore.collection('orders')
      .where('status', '==', status) 
      .where('createdAt', '>=', start)
      .where('createdAt', '<=', end)
      .get()  
      .then(snapshot => {              
        snapshot.forEach(docs => {
            orderArray.push(docs.data())
        })
        console.log(orderArray); //outputs the orders correctly
        return orderArray;
       }).catch(error => {
        console.log(error)
       })
}

I want to call getAllOrders to get the orders and output them to the console. I tried the 2 following methods to get the orders to print. Both output undefined.

Method 1

const onSubmit = async () => {
    props.firebase.getAllOrders().then((orders) => {
        console.log(orders);
    })
}

Method 2

const onSubmit = async () => {
    const orders = await props.firebase.getAllOrders()
    console.log(orders)

}

The first thing that is outputted is undefined and then the correct order array, so the await is not working. I know I'm missing something to get this to work. What should I change it to make it work?

paul
  • 11
  • 1
  • i looked at the referenced post and i am using the 2 methods that are recommended: async/await and promises. None are working, which is why I'm posting this question. please help – paul Dec 11 '21 at 00:09
  • You need to return the promise that's created by `this.firestore.collection('orders')/* etc*/`. So do `return this.firestore.collection('orders')/* etc*/`. – Nicholas Tower Dec 11 '21 at 00:16
  • so i have like 2 return statements now – paul Dec 11 '21 at 00:28

0 Answers0