我有以下代码,它从web url中提取数据,向用户显示数据,并更新mysql数据库-除了一个小问题外,它运行良好:
function RunScrapingIndexWatch() {
myhttp.get('http://www.url.com',
function (_html) {
if (_html && _html.length > 10) {
news.indexwatch = [];
$ = cheerio.load(_html);
status = false;
$('td.text21').each(function () {
status = true;
var price1 = parseFloat($(this).text().substr($(this).text().indexOf("Nifty :") + 7, 7).trim());
var abc = stringHelper.getIndiaTime();
var IWTime = abc.toLocaleTimeString();
news.indexwatch.push({
'price1': price1,
'IWTime': IWTime,
});
var post = {
'price1': price1,
'IWTime': IWTime
};
connection.query('INSERT INTO IW SET ?', post, function (err,result){
if (err)
{console.log("IW sql insert error : " +price1 +IWTime);}
else {
console.log("IW data inserted : " +price1 +" | " +IWTime);
}
});
});
if (status) {
io.emit('news', news);
}
if (timerIndexWatch) {
clearTimeout(timerIndexWatch);
}
timerIndexWatch = setTimeout(RunScrapingIndexWatch, config.DelayExtractIndexWatch);
}
});
}
问题是,在web显示(由上面的代码"news.indexwatch.push"生成)中,IWTime的值在短时间内显示为未定义-我想这是在运行mysql连接查询时发生的。mysql数据库正在正确更新。
有没有办法在io.emit新闻操作之后运行mysql插入查询?有什么建议吗?
除非您可以使用来自.emit()
函数的回调,否则不会。
为什么不等到MySQL将.emit()
放在connection.query()
回调中完成操作后再发出信息:
function RunScrapingIndexWatch() {
myhttp.get('http://www.url.com', function(_html) {
if (_html && _html.length > 10) {
news.indexwatch = [];
$ = cheerio.load(_html);
status = false;
$('td.text21').each(function() {
status = true;
var price1 = parseFloat($(this).text().substr($(this).text().indexOf("Nifty :") + 7, 7).trim()),
abc = stringHelper.getIndiaTime(),
IWTime = abc.toLocaleTimeString(),
post = {
'price1': price1,
'IWTime': IWTime
};
connection.query('INSERT INTO IW SET ?', post, function(err, result) {
if (err) {
console.log("IW sql insert error : " + price1 + IWTime);
} else {
console.log("IW data inserted : " + price1 + " | " + IWTime);
}
news.indexwatch.push(post);
if (status) io.emit('news', news);
}); // connection.query()
if (timerIndexWatch) clearTimeout(timerIndexWatch);
timerIndexWatch = setTimeout(RunScrapingIndexWatch, config.DelayExtractIndexWatch);
}); // $.each()
} // if (_html && ...)
}); // myhttp.get()
}; // RunScrapingIndexWatch