【问题标题】:how to access an outside variable inside a forEach loop如何在 forEach 循环中访问外部变量
【发布时间】:2019-02-13 01:34:40
【问题描述】:

我正在尝试为从 forEach 循环外部声明的变量设置一个值,但我收到了以下警告:标识符 'arr' 永远不会重新分配;使用'const'而不是'let'.tslint(prefer-const)......当我部署我的代码时,我只得到一个空变量

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
    })
})

【问题讨论】:

  • forEach 不是异步函数,因此您不能等待它。您也不能将异步函数传递给它并期望它等待函数中的承诺。
  • 实际上,await 是让它发挥作用的绝望尝试? Doug 的正确做法是什么?
  • 将所有的promise收集到一个数组中,使用Promise.all等待所有的结果。

标签: typescript firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

用这段代码得到了预期的结果:

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})

})

【讨论】:

    猜你喜欢
    • 2012-11-11
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 2013-11-29
    • 2021-01-21
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    相关资源
    最近更新 更多