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?