node.js异步问题? [英] node.js asynchronous issue?
问题描述
基本上我想遍历现有的arrickers以获取每个符号
Basically I want to loop through existing arrtickers to get each symbol
然后读取每个符号url中的内容并将其保存到本地目录中.
Then read the content inside each symbol url and save the content into local dir.
在php中,它将逐步打印出每个股票代码和每个符号.
In php, it will print out each ticker and each symbol in step by step.
但是在节点中,序列混乱了.
But in node, the sequences are mess up.
它将首先打印出所有url_optionable ...
it will print out all the url_optionable first...
然后有时会打印console.log('path:'+ file),有时会打印console.log(文件已保存!");
then sometimes print console.log('path: ' + file), sometimes print console.log("The file was saved!");
每次通过fs.writefile函数运行,未检测到sym值,保存的文件显示为msn-.html
Everytime run through fs.writefile function, sym value is not detected, the saved file is show as msn-.html
for(var v=0;v<arrtickers.length;v++)
{
var arrticker= arrtickers[v].split('@@');
var sym= $.trim(arrticker[1]);
url_optionable= "http://sample.com/ns/?symbol="+sym;
console.log('url_optionable: ' + url_optionable);
request({ uri:url_optionable }, function (error, response, body) {
if (error && response.statusCode !== 200) {
console.log('Error contacting ' + url_optionable)
}
jsdom.env({
html: body,
scripts: [
jqlib
]
}, function (err, window) {
var $ = window.jQuery;
var data= $('body').html();
var file= "msn-"+sym+".html";
console.log('path: ' + file);
fs.writeFile(file, data, function(err) {
if(err) {
console.log(err);
}
else
{
console.log("The file was saved!");
}
});
});
});
}
推荐答案
ZeissS是正确的.基本上,您不能在异步调用的回调函数中的for循环中使用声明的变量,因为它们都将被设置为循环中的最后一个值.因此,在您的代码中, url_optionable
和 sym
将对应于 arrtickers [arrtickers.length-1]
.
ZeissS is right. Basically, you can't use variables declared inside the for loop in a callback function to an asynchronous call, because they will all be set to the last value in the loop. So in your code, url_optionable
and sym
will correspond to arrtickers[arrtickers.length - 1]
.
两种用途(如ZeissS建议):
Either use (as ZeissS suggests):
arrtickers.forEach(function(arrticker) {
// Get symbol and url, make request etc
});
或声明一个使用 sym
并执行请求的函数,然后在您的循环中调用该函数:
Or declare a function which takes sym
and does the request, and call that in your loop:
function getSymbol(symbol) {
// Request url and read DOM
}
for(var v=0;v<arrtickers.length;v++) {
var arrticker = arrtickers[v].split('@@');
var sym = $.trim(arrticker[1]);
getSymbol(sym);
}
我个人会选择 forEach
解决方案.
Personally, I would opt for the forEach
solution.
这篇关于node.js异步问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!