0
votes

I'm trying to set an value to a variable declared outside from a forEach loop but I'm getting this warn: Identifier 'arr' is never reassigned; use 'const' instead of 'let'.tslint(prefer-const)... When i deploy my code I just get an empty variable

import * as functions from "firebase-functions"
import * as admin from "firebase-admin"

admin.initializeApp()

export const test = functions.https.onRequest(async (req, res) => {

    const stores = await admin.firestore().collection('stores').get()

    let arr: boolean[] = []

    // tslint:disable-next-line: no-void-expression
    await stores.forEach(async (store) => {
        const sales = await store.ref.collection('sales').get()
        arr.push(sales.empty)
    })

    console.log(arr);

    res.status(200).send({
    arr: arr
    })
})
1
forEach isn't an async function, so you can't await it. You also can't pass an async function to it and expect it to wait on promises within the function.Doug Stevenson
Actually that await was an desperate attempt to make it work? What is the correct approach to do that Doug?Caio Reis
Collect all the promises into an array and use Promise.all to wait for all of the results.Doug Stevenson

1 Answers

0
votes

got the expected results with this code:

export const test = functions.https.onRequest(async (req, res) => {

    const fetchStores = await admin.firestore().collection('stores').get()
    const arr = []

    for (const store of fetchStores.docs) {
        const sales = await store.ref.collection('sales').get()
        arr.push(sales.empty)
    }

    res.status(200).send({arr: arr})

})