我正在研究从API获取数据并使用 Socket.io 将其显示到UI的脚本,该脚本同时运行。
const express = require("express");
const app = express();
const http = require("http").Server(app);
const io = require("socket.io")(http);
function mainBody() {
oldTime = new Date().getTime();
// Set the headers
let headers = {
Authorization: "Bearer XXXXXXXXXXX",
"Content-Type": "application/json"
};
let n = 0;
let r = 0;
j = 0;
const handleResultsForRequest = function(err, response, body) {
if (!err && response.statusCode === 200) {
const js = JSON.parse(body);
if (undefined !== JSON.stringify(js)) {
const data_key = js.eventId + "_" + JSON.parse(body).start;
data[data_key] = js;
} else console.log("status code:" + response.statusCode);
}
};
let array = [
103307565,
103771668,
103621400,
103675790,
103887500,
];
itemCal = 0;
array.forEach(async function(item, index, array) {
n = 0;
// Configure the request
options = {
url: "https://api.XXXXXXXXXXXXX",
method: "GET",
headers: headers,
qs: { eventId: item, pricingsummary: true, rows: "250", start: n }
};
Request(options, function(err, response, body) {
itemCal++;
if (err) {
console.log("ERROR: " + err);
} else {
try {
const js = JSON.parse(body);
r = js.totalListings;
r = Math.floor(r / 250) + 1;
n = 0;
for (let i = 0; i < r; i++) {
// Configure the request
options = {
url:
"https://api.XXXXXXXXXXXXXXXXXXXX",
method: "GET",
headers: headers,
qs: { eventId: item, pricingsummary: true, rows: "250", start: n }
};
n += 250;
Request(options, handleResultsForRequest);
}
} catch (e) {
console.log(e);
}
}
if (itemCal == array.length) {
var currentTime = new Date().getTime();
io.emit("data",diff);
mainBody();
}
});
});
}
mainBody();
在文件中,具有5个ID的数组在循环中执行,并且在所有循环执行后脚本的末尾都有 socket.emit(),并在发出数据mainBody()之后再次运行,并且执行将连续运行,并在每次执行时将数据传递给客户端。
问题::目前,我在数组中有5个ID的示例中显示此脚本在500个ID之前可以正常工作,但我输入了500至550个ID,然后返回此错误。
socket hang up
at createHangUpError (_http_client.js:331:15)
at TLSSocket.socketOnEnd (_http_client.js:423:23)
at emitNone (events.js:111:20)
at TLSSocket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickCallback (internal/process/next_tick.js:181:9) code: 'ECONNRESET' }
并停止将数据传递给客户端。任何帮助将不胜感激。 :)预先感谢。