【发布时间】:2017-12-26 18:42:43
【问题描述】:
我是从 Javascript 开始的,我需要帮助来弄清楚如何使这段代码在循环通过 for 循环时同步。 基本上我正在做的是在 for 循环中发出多个 POST 请求,然后我使用库 X-Ray 报废数据,最后我将结果保存到 Mongo 数据库。 输出没问题,但它以无序的方式出现并突然挂起,我必须使用 ctrl+C 强制关闭。这是我的功能:
function getdata() {
const startYear = 1996;
const currentYear = 1998; // new Date().getFullYear()
for (let i = startYear; i <= currentYear; i++) {
for (let j = 1; j <= 12; j++) {
if (i === startYear) {
j = 12;
}
// Form to be sent
const form = {
year: `${i}`,
month: `${j}`,
day: '01',
};
const formData = querystring.stringify(form);
const contentLength = formData.length;
// Make HTTP Request
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded',
},
uri: 'https://www.ipma.pt/pt/geofisica/sismologia/',
body: formData,
method: 'POST',
}, (err, res, html) => {
if (!err && res.statusCode === 200) {
// Scrapping data with X-Ray
x(html, '#divID0 > table > tr', {
date: '.block90w',
lat: 'td:nth-child(2)',
lon: 'td:nth-child(3)',
prof: 'td:nth-child(4)',
mag: 'td:nth-child(5)',
local: 'td:nth-child(6)',
degree: 'td:nth-child(7)',
})((error, obj) => {
const result = {
date: obj.date,
lat: obj.lat.replace(',', '.'),
lon: obj.lon.replace(',', '.'),
prof: obj.prof == '-' ? null : obj.prof.replace(',', '.'),
mag: obj.mag.replace(',', '.'),
local: obj.local,
degree: obj.degree,
};
// console.log(result);
upsertEarthquake(result); // save to DB
});
}
});
}
}
}
我想我必须使用承诺或回调,但我不明白如何做到这一点,我已经尝试使用异步等待但没有成功。如果需要提供任何其他信息,请告诉我,谢谢。
【问题讨论】:
标签: javascript node.js web-scraping request x-ray