我对JS中的承诺还是个新手,我想知道我做错了什么。我得到以下错误:UnhandledPromiserEjectionWarning:ReferenceError:history is not defined
for第二个console.log(history[0])
。有趣的是,第一个控制台日志打印histroy[0],但第二个控制台日志(在if中)返回此错误。在输入if之前,历史响应不应该是有效的吗,因为我已经检查了它是否为空以及是否定义了第一个对象?
history = await api.getHistory(url)
console.log(history[0])
if (history[0] !== undefined && history.length > 0) {
// Do require checks
console.log(history[0])
我的盖氏理论方法:
async function getHistory(url) {
const stationHistory = []
return new Promise((function (resolve, reject) {
axios({
method: 'get',
url: url,
responseType: 'stream'
}).then(function(response) {
if (response.headers['content-type'] !== 'application/force-download') {
reject('Invalid parameters were supplied to request')
}
response.data.pipe(csv())
.on("data", function (row) {
stationHistory.push(row)
})
.on("end", function () {
if (stationHistory.length > 0 && Object.keys(stationHistory[0]).length > 9) {
resolve(stationHistory)
} else {
resolve([]) // Resolve to empty data
}
})
.on("error", reject)
})
}))
}
问题:if语句中未定义历史记录
你一开始就不得不犯错误。
尝试定义历史记录
,如下所示:
const history = await api.getHistory(url)
该错误表示您没有定义名为history
的变量。