【发布时间】: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