Firebase Cloud Functions随机报错:TypeError: newMatches.forEach不是函数
解决Cloud Function随机出现的
TypeError: newMatches.forEach is not a function错误 问题原因
这个随机错误的核心是**getNewRLMatches函数返回的newMatches并不总是数组**,导致无法调用forEach方法。可能的触发场景:
- 目标API偶尔返回非数组格式响应(比如出错时返回包含错误信息的对象)
- API返回异常状态码(如5xx/4xx),但代码未做校验,直接解析了错误响应的JSON内容
修复步骤
- 添加API响应校验:确保请求成功后再解析JSON,异常时捕获错误
- 强制校验返回值类型:调用
forEach前确认newMatches是数组 - 优化异步逻辑:用
await替代.then,简化代码结构并避免异步回调的潜在问题
修复后的代码
const db = getFirestore(); const functions = require("firebase-functions"); // 确保FieldValue已正确导入 const { FieldValue } = require("firebase-admin/firestore"); exports.getAllMatches = functions .region("europe-west1") .runWith({ failurePolicy: true }) .pubsub.schedule("*/1 * * * *") .onRun(async (context) => { /** * 获取RL匹配数据 * @returns {Array} 匹配数据数组,请求失败时抛出错误 */ async function getNewRLMatches() { const rlUrl = "https://apiURL"; const rlResponse = await fetch(rlUrl); // 校验API响应状态 if (!rlResponse.ok) { throw new Error(`API请求失败:状态码 ${rlResponse.status}`); } const newRLMatches = await rlResponse.json(); // 校验返回值是否为数组 if (!Array.isArray(newRLMatches)) { throw new Error(`API返回非数组格式:${JSON.stringify(newRLMatches)}`); } return newRLMatches; } /** * 批量上传匹配数据 * @param {Object[]} arrMatchesToAdd 待写入的文档操作数组 * @returns {Promise} 批量写入的Promise */ async function uploadMatches(arrMatchesToAdd) { await Promise.all(arrMatchesToAdd); console.log("Write succeeded !"); } try { const newMatches = await getNewRLMatches(); const rlMatchesToAdd = []; newMatches.forEach((newMatch) => { const dateNow = new Date(); const dateModified = new Date(newMatch["modified_at"]); const diff = dateNow - dateModified; const newMatchID = newMatch["id"].toString(); if (diff < 180e3) { newMatch["added_at"] = FieldValue.serverTimestamp(); rlMatchesToAdd.push( db.collection("RL Matches") .doc(newMatchID) .set(newMatch) ); } }); const arrLength = rlMatchesToAdd.length; if (arrLength === 0) { console.log("No RL match have been recently modified"); } else { console.log(arrLength, " RL matches have been recently modified"); } await uploadMatches(rlMatchesToAdd); } catch (error) { console.error("函数执行出错:", error); // 抛出错误让Cloud Functions记录失败,便于后续排查 throw error; } });
额外说明
- 新增的错误捕获逻辑会在API异常或返回格式错误时,将详细信息打印到日志,方便定位具体问题
- 改用
await后,代码执行顺序更清晰,避免了原代码中onRun函数可能在异步操作完成前就结束的问题 - 注意确认
FieldValue已正确导入,原代码中缺失该导入可能导致Firestore写入失败
内容的提问来源于stack exchange,提问作者simsab
相关产品推荐
相关产品推荐

