Madhur Ahuja
Madhur Ahuja

Reputation: 22709

Sequential execution in node.js using arrays

I was learning sequential execution in node.js and came across an interesting problem.

Below is my code. Basically, I have 5 RSS Feeds in an array and I am trying to output titles of them sequentially. For this purpose, I have created an array of functions and utilizing this helper function from a book:

function next(err, result)
{
    if(err) throw new Error(err);

    var currentTask = tasks.shift();

    if(currentTask)
    {
        currentTask(result);
    }

}

Now, my program works correctly, If I prepare array as :

tasks = [

function(){handle(urls[0])},
function(){handle(urls[1])},
function(){handle(urls[2])},
function(){handle(urls[3])},
function(){handle(urls[4])}

];

However it outputs in random order and not sequential, if I prepare as:

tasks = [

handle(urls[0]),
handle(urls[1]),
handle(urls[2]),
handle(urls[3]),
handle(urls[3]),

];

What is the difference between above 2 arrays?

Full Code:

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();

Upvotes: 0

Views: 194

Answers (1)

Bergi
Bergi

Reputation: 665555

What is the difference between above 2 arrays?

Well, the first is an array of functions, while the second is an array of undefineds.

but how come it still executes and outputs in random order though?

You are executing it (not the next() queue), and they execute in parallel, so the async callbacks come back in non-deterministic order.

Upvotes: 1

Related Questions