Don't use map
if you're not using its return value. There's no point in having your code create an array you're just immediately going to throw away.
If you want the calls to get the counts to run in parallel, you can use an array of promises from map
with Promise.all
:
async getPopular() {
return await tryCatchWithApolloErrorAsync(async () => {
const popular = await adminService
.firestore()
.collection(api.counters)
.doc('companies-by-categories')
.collection('categories')
.get()
let data: Popular[] = []
await Promise.all(popular.docs.map(async element => { // `async` function
const count = await getCount(element.ref) // returns a promise
if (count > 0) {
data.push({
id: parseInt(element.id),
amount: count
})
}
}))
return data
})
},
Or another way to do that is with filter
:
async getPopular() {
return await tryCatchWithApolloErrorAsync(async () => {
const popular = await adminService
.firestore()
.collection(api.counters)
.doc('companies-by-categories')
.collection('categories')
.get()
let data: Popular[] = await Promise.all(popular.docs.map(async element => ({
id: parseInt(element.id),
count: await getCount(element.ref)
})));
return data.filter(({count}) => count > 0)
})
},
If you want them to run sequentially, use a for-of
loop:
async getPopular() {
return await tryCatchWithApolloErrorAsync(async () => {
const popular = await adminService
.firestore()
.collection(api.counters)
.doc('companies-by-categories')
.collection('categories')
.get()
let data: Popular[] = []
for (const element of popular.docs) {
const count = await getCount(element.ref)
if (count > 0) {
data.push({
id: parseInt(element.id),
amount: count
})
}
}
return data
})
},