gpt4 book ai didi

node.js - readline.createInterface({}).on({}) 内的变量未更新

转载 作者:太空宇宙 更新时间:2023-11-03 23:55:18 28 4
gpt4 key购买 nike

尝试使用 .csv 文件中的值构建请求正文,但我的点数组未更新。我已经为 on() 函数内部和末尾的点数组完成了 console.log() ,并且值按预期存在。但我在 on() 之外console.log,它说数组是空的。

我知道这是一个范围问题,但对 Node.js 不太熟悉,所以无法弄清楚。谢谢。

// Detect anomalies in your spreadsheet
var points = []
var dict = {}
// Read the .csv file, convert date to Date object and number to float.
readline.createInterface({
input: fs.createReadStream(CSV_FILE),
terminal: false
}).on('line', function(line) {
var row = line.split(",")
dict[new Date(row[0])] = parseFloat(row[1])
points.push(dict)
});

// Create request body for API call
let body = { series: points, granularity: 'hourly' }
// Make the call
anomalyDetectorClient.entireDetect(body)
.then((response) => {
for (item in response.isAnomaly) {
if (item) {
console.log("An anomaly was detected from the series.")
console.log("Value: " + response.expectedValues[response.indexOf(item)])
}
}
}).catch((error) => {
console.log(error)
})

更新:

我正在尝试将异步函数移至 on() 中,因此 points[] 中包含值...但请求中存在错误的正文,我的点数组每次推送时都会采用累积字典而不是新字典。因此,在我可以再次查看最后一个 on() 之外未更新的 points[] 之前,需要先解决这个问题。

当前代码,我将 API 调用移至最后一个 on() 函数中(之前它位于函数外部,前面有一个 await):

async function main() {
let CSV_FILE = './request-data.csv'

// Detect anomalies in your spreadsheet
var points = []

// Read the .csv file
await readline.createInterface({
input: fs.createReadStream(CSV_FILE),
terminal: false
}).on('line', function(line) {
var row = line.split(",")
// Convert date to Date object and number to float.
var date = new Date(row[0])
var dict = {}
dict[date] = parseFloat(row[1])
points.push(dict)
console.log(points)
}).on('close', function() {
// Create request body for API call
let body = { series: points, granularity: 'hourly' }

console.log("Body series: " + body.series.timestamp + "Body granularity: " + body.granularity)
// Make the call
anomalyDetectorClient.entireDetect(body)
.then((response) => {
for (item in response.isAnomaly) {
if (item) {
console.log("An anomaly was detected from the series.")
console.log("Value: " + response.expectedValues[response.indexOf(item)])
}
}
}).catch((error) => {
console.log(error)
})
})

更新2:

在答案中使用新代码,出现新错误:正文系列:未定义正文粒度:每小时
{ 错误:时间点应按小时粒度均匀分布,间隔为 1 gr,缺失点比例应小于 10%,2018-03-01 00:00:00 至 2018-04-16 00:00:00 之间至少应有 994 个点,但得到了 47 个点。
这是什么意思?

因为主体对象看起来不错而感到困惑,但打印出错误:

{ Error: Time points should be uniformly spaced in time in hourly granularity with 1 gran as interval, ratio of missing points should be less than 10%, between 2018-03-01 00:00:00 and 2018-04-16 00:00:00 there should be at least 994 points, but got 47 points.
at new RestError (C:\Users\v-wiazur\Desktop\Anomaly Detector\node_modules\@azure\ms-rest-js\dist\msRest.node.js:1399:28)
at C:\Users\v-wiazur\Desktop\Anomaly Detector\node_modules\@azure\ms-rest-js\dist\msRest.node.js:2494:37
at process._tickCallback (internal/process/next_tick.js:68:7)
code: 'InvalidSeries',
statusCode: 400,
request:
WebResource {
streamResponseBody: false,
url:
'https://winonaanomalydetector.cognitiveservices.azure.com/anomalydetector/v1.0/timeseries/entire/detect',
method: 'POST',
headers: HttpHeaders { _headersMap: [Object] },
body:
'{"series":[{"timestamp":"2018-03-01T00:00:00.000Z","value":32858923},{"timestamp":"2018-03-02T00:00:00.000Z","value":29615278},{"timestamp":"2018-03-03T00:00:00.000Z","value":22839355},{"timestamp":"2018-03-04T00:00:00.000Z","value":25948736},{"timestamp":"2018-03-05T00:00:00.000Z","value":34139159},{"timestamp":"2018-03-06T00:00:00.000Z","value":33843985},{"timestamp":"2018-03-07T00:00:00.000Z","value":33637661},{"timestamp":"2018-03-08T00:00:00.000Z","value":32627350},{"timestamp":"2018-03-09T00:00:00.000Z","value":29881076},{"timestamp":"2018-03-10T00:00:00.000Z","value":22681575},{"timestamp":"2018-03-11T00:00:00.000Z","value":24629393},{"timestamp":"2018-03-12T00:00:00.000Z","value":34010679},{"timestamp":"2018-03-13T00:00:00.000Z","value":33893888},{"timestamp":"2018-03-14T00:00:00.000Z","value":33760076},{"timestamp":"2018-03-15T00:00:00.000Z","value":33093515},{"timestamp":"2018-03-16T00:00:00.000Z","value":29945555},{"timestamp":"2018-03-17T00:00:00.000Z","value":22676212},{"timestamp":"2018-03-18T00:00:00.000Z","value":25262514},{"timestamp":"2018-03-19T00:00:00.000Z","value":33631649},{"timestamp":"2018-03-20T00:00:00.000Z","value":34468310},{"timestamp":"2018-03-21T00:00:00.000Z","value":34212281},{"timestamp":"2018-03-22T00:00:00.000Z","value":38144434},{"timestamp":"2018-03-23T00:00:00.000Z","value":34662949},{"timestamp":"2018-03-24T00:00:00.000Z","value":24623684},{"timestamp":"2018-03-25T00:00:00.000Z","value":26530491},{"timestamp":"2018-03-26T00:00:00.000Z","value":35445003},{"timestamp":"2018-03-27T00:00:00.000Z","value":34250789},{"timestamp":"2018-03-28T00:00:00.000Z","value":33423012},{"timestamp":"2018-03-29T00:00:00.000Z","value":30744783},{"timestamp":"2018-03-30T00:00:00.000Z","value":25825128},{"timestamp":"2018-03-31T00:00:00.000Z","value":21244209},{"timestamp":"2018-04-01T00:00:00.000Z","value":22576956},{"timestamp":"2018-04-02T00:00:00.000Z","value":31957221},{"timestamp":"2018-04-03T00:00:00.000Z","value":33841228},{"timestamp":"2018-04-04T00:00:00.000Z","value":33554483},{"timestamp":"2018-04-05T00:00:00.000Z","value":32383350},{"timestamp":"2018-04-06T00:00:00.000Z","value":29494850},{"timestamp":"2018-04-07T00:00:00.000Z","value":22815534},{"timestamp":"2018-04-08T00:00:00.000Z","value":25557267},{"timestamp":"2018-04-09T00:00:00.000Z","value":34858252},{"timestamp":"2018-04-10T00:00:00.000Z","value":34750597},{"timestamp":"2018-04-11T00:00:00.000Z","value":34717956},{"timestamp":"2018-04-12T00:00:00.000Z","value":34132534},{"timestamp":"2018-04-13T00:00:00.000Z","value":30762236},{"timestamp":"2018-04-14T00:00:00.000Z","value":22504059},{"timestamp":"2018-04-15T00:00:00.000Z","value":26149060},{"timestamp":"2018-04-16T00:00:00.000Z","value":35250105}],"granularity":"hourly"}',
query: undefined,
formData: undefined,
withCredentials: false,
abortSignal: undefined,
timeout: 0,
onUploadProgress: undefined,
onDownloadProgress: undefined,
proxySettings: undefined,
operationSpec:
{ httpMethod: 'POST',
path: 'timeseries/entire/detect',
urlParameters: [Array],
requestBody: [Object],
responses: [Object],
serializer: [Serializer] } },
response:
{ body:
'{"code":"InvalidSeries","message":"Time points should be uniformly spaced in time in hourly granularity with 1 gran as interval, ratio of missing points should be less than 10%, between 2018-03-01 00:00:00 and 2018-04-16 00:00:00 there should be at least 994 points, but got 47 points."}\n',
headers: HttpHeaders { _headersMap: [Object] },
status: 400 },
body:
{ code: 'InvalidSeries',
message:
'Time points should be uniformly spaced in time in hourly granularity with 1 gran as interval, ratio of missing points should be less than 10%, between 2018-03-01 00:00:00 and 2018-04-16 00:00:00 there should be at least 994 points, but got 47 points.' } }

最佳答案

您的阵列正在更新。如果您在 line 事件处理程序中执行 console.log(points) ,您将看到它每次都会累积日期。

问题在于您在填充数组之前在错误的位置查看数组。 readline 接口(interface)是异步的。因此,您调用 readline.createInterface() 并为 line 事件设置事件处理程序,然后您的代码就会继续运行。在 readline 操作完成其工作之前,您将立即调用 anomalyDetectorClient.entireDetect()

解决方案是等到 readline 接口(interface)完成读取整个文件并完全填充您的 points 数组,然后再尝试使用 points 数组。

这是一种方法,您可以在 readline 接口(interface)的 close 事件处理程序中处理 points 数组:

// Detect anomalies in your spreadsheet
var points = [];
var dict = {};
// Read the .csv file, convert date to Date object and number to float.
readline.createInterface({
input: fs.createReadStream(CSV_FILE),
terminal: false
}).on('line', function(line) {
var row = line.split(",");
let point = {
timestamp: new Date(row[0]),
value: parseFloat(row[1])
};
dict[point.date] = point.value;
points.push(point);
console.log(points);
}).on('close', function() {
// now we're done reading the file
console.log(points); // all the points are here

// now process the points
// Create request body for API call
let body = { series: points, granularity: 'hourly' };
// Make the call
anomalyDetectorClient.entireDetect(body).then((response) => {
for (let item in response.isAnomaly) {
if (item) {
console.log("An anomaly was detected from the series.")
console.log("Value: " + response.expectedValues[response.indexOf(item)])
}
}
}).catch((error) => {
console.log(error)
});

}).on('error', function(err) {
// handle errors here
console.log(err);
});

仅供引用,您真的确定应该在 response.isAnomaly 中使用 item 吗? in 不适用于数组,它适用于对象的属性。它对数组有点,有点适用,但它也不能工作很多次。 for/of 是专门为数组构建的,如 for (let item of response.isAnomaly) {...} 中所示。另外,对于数组,in 获取的是值的索引,而不是数组值。 of 获取通常是您想要的数组值。

关于node.js - readline.createInterface({}).on({}) 内的变量未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57504586/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com