我正在学习 Node.js 中的顺序执行,并遇到了一个有趣的问题。
下面是我的代码。基本上,我在一个数组中有 5 个 RSS 提要,并且我试图按顺序输出它们的标题。为此,我创建了一系列函数并利用书中的这个辅助函数:
function next(err, result)
{
if(err) throw new Error(err);
var currentTask = tasks.shift();
if(currentTask)
{
currentTask(result);
}
}
现在,我的程序可以正常工作,如果我将数组准备为:
tasks = [
function(){handle(urls[0])},
function(){handle(urls[1])},
function(){handle(urls[2])},
function(){handle(urls[3])},
function(){handle(urls[4])}
];
但是,如果我准备如下,它会以随机顺序而不是顺序输出:
tasks = [
handle(urls[0]),
handle(urls[1]),
handle(urls[2]),
handle(urls[3]),
handle(urls[3]),
];
以上两个数组有什么区别?
完整代码:
var request = require('request');
var parser = require('htmlparser');
var urls = ['http://psychcentral.com/blog/feed/rss2/', 'http://davidicuswong.wordpress.com/feed/', 'http://www.theglobalconversation.com/blog/?feed=rss2', 'http://happiness-project.com/feed', 'http://www.marriagemissions.com/feed/'];
function handle(url)
{
request(url, function(error, response, body)
{
if (!error && response.statusCode == 200)
{
var handler = new parser.RssHandler();
var rssParser = new parser.Parser(handler);
rssParser.parseComplete(body);
if (handler.dom.items.length)
{
var item = handler.dom.items.shift();
console.log(item.title);
console.log(item.link);
}
next(null, null);
}
});
}
function next(err, result)
{
if(err) throw new Error(err);
var currentTask = tasks.shift();
if(currentTask)
{
currentTask(result);
}
}
tasks = [
function(){handle(urls[0])},
function(){handle(urls[1])},
function(){handle(urls[2])},
function(){handle(urls[3])},
function(){handle(urls[4])}
];
next();
最佳答案
What is the difference between above 2 arrays?
嗯,第一个是函数数组,而第二个是未定义
数组。
but how come it still executes and outputs in random order though?
您正在执行它(而不是next()
队列),并且它们并行执行,因此异步回调以不确定的顺序返回。
关于javascript - 使用数组在node.js中顺序执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25166812/