Reputation: 552
I have this function here in a separate file, where:
export const getListOfChannels = (id) => {
const channels = []
firestore.collection("channels").where("channelId", "==", id).get().then(querySnapshot => {
querySnapshot.forEach(doc => {
channels.push(doc.data().id)
})
})
return channels
}
And in another file, I'm doing:
// This is returning an empty array
const returnFromFirebase = getListOfChannelsIdWithCommunityId(id)
It wasn't supposed to return an empty array, because if I do a console.log(doc.data().id)
I can see the data.
Am I doing something wrong?
Upvotes: 1
Views: 2549
Reputation: 317828
Firebase APIs (and any API that returns a promise) are asynchronous and return immediately, before the query is complete. The callback you provide via then
is invoked some time later, after the results are available. There is no guarantee how quickly this will happen. As such, it's not possible to make a function that returns the query results immediately.
For asynchronous calls, what you're supposed to do is make your wrapper function also return a promise, and make the caller use that promise to get the results:
export const getListOfChannels = (id) => {
return firestore.collection("channels").where("channelId", "==", id).get();
}
getListOfChannelsIdWithCommunityId(id).then(querySnapshot => {
querySnapshot.forEach(doc => {
channels.push(doc.data().id)
})
})
There are a lot of variations on how to do this, but there is no alternative to dealing with that promise asynchronously. I strongly suggest learning how promises work, as it is critical to writing effective JavaScript.
Upvotes: 3
Reputation: 13702
getListOfChannels
is having code that does async call and you are returning channels
outside of then
and therefore it will always be empty.
So, return the promise
export const getListOfChannels = (id) => {
const channels = []
return firestore.collection("channels").where("channelId", "==", id).get().then(querySnapshot => {
querySnapshot.forEach(doc => {
channels.push(doc.data().id)
})
return channels;
})
}
And in Another file access it in then
block
let returnFromFirebase = [];
getListOfChannelsIdWithCommunityId(id).then((res) => {
returnFromFirebase = res;
});
Upvotes: 1