【发布时间】:2020-11-02 15:32:25
【问题描述】:
我是 Javascript 新手,不知道为什么会出错。
在下面的代码中,在 一些 运行时,它会声称 playerWinRates 未定义
TypeError: Cannot read property 'lost' of undefined
at file:///Users/bergholm/projects/FACEITDiscordBot/faceIt.js:296:36
at Array.forEach (<anonymous>)
at getPastMatchesByPlayer (file:///Users/bergholm/projects/FACEITDiscordBot/faceIt.js:284:16)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
undefined
(node:35193) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
(node:35193) UnhandledPromiseRejectionWarning: TypeError: Cannot convert undefined or null to object
at Function.keys (<anonymous>)
at bestWinRate (file:///Users/bergholm/projects/FACEITDiscordBot/faceIt.js:341:20)
at Client.<anonymous> (file:///Users/bergholm/projects/FACEITDiscordBot/bot.js:126:15)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:35193) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
我说的代码sn-p在这里,在playerWinRates[map][mapWL[map]] += 1上失败了
async function getPastMatchesByPlayer(playerId, numMatches = 20) {
const response = await axios.get(
"https://open.faceit.com/data/v4/players/" +
playerId +
"/history?game=csgo&offset=0&limit=" +
numMatches
)
const playerWinRates = {
de_cache: { won: 0, lost: 0 },
de_dust2: { won: 0, lost: 0 },
de_mirage: { won: 0, lost: 0 },
de_nuke: { won: 0, lost: 0 },
de_overpass: { won: 0, lost: 0 },
de_train: { won: 0, lost: 0 },
de_inferno: { won: 0, lost: 0 },
de_vertigo: { won: 0, lost: 0 },
}
let matchIds = []
let statsPromises = []
response.data.items.forEach((match) => {
matchIds.push(match.match_id)
statsPromises.push(parseMatchWon(match, playerId))
})
const listOfResults = await Promise.all(statsPromises)
listOfResults.forEach((mapWL) => {
if (!mapWL) { // If null -- failed to get match, so ignore it
console.log("Went into null/undefined")
return
}
let map = Object.keys(mapWL)[0]
playerWinRates[map][mapWL[map]] += 1
})
// The match id's are provided so that in the future they could be parsed to allow for more weight on different matches
return { playerWinRates: playerWinRates, matchIds: matchIds }
}
编辑:删除了功能描述,因为它占用了大量空间并且对这项任务没有帮助
【问题讨论】:
-
在
playerWinRates[map][mapWL[map]] += 1之前添加console.log(mapWL, map)以查看失败的值。错误之前的最后一个日志将显示最后一个值。
标签: javascript node.js json constants es6-promise