Search code examples
javascriptmeteornode-fibers

Meteor (Fibers) loop and callback


Meteor fibers "sync" mode is driving me crazy. Here is a simple code example :

var feedsData = feeds.fetch(); // [{_id: "1234"}, {_id: "6789", url: "http://...."}]
for(var i = 0, len = feedsData.length; i < len; i++) {
    var feed = feedsData[i];
    parser.parseURL(feed.url, function(err, out){
        console.log(feed._id, i); // outputs "6789" and "2" each times
    });
}

I don't understand how to make this work. The callback is called after the loop is over, but the internal internal variables such as feed should be preserved... and they are not.

The url parsed are good (the first one, then the second one), but then i can't update my data since I don't have the good _id in the callback.

The wanted output would be: "1234" "0" and "6789" "1", not "6789" "2" both times... How would you make this in Meteor / Fiber code ?


Solution

  • Another way to do it in the "fiber"(and it is probably better than the answer with "future" I posted above) :

    var feedsData = feeds.fetch(); // [{_id: "1234"}, {_id: "6789", url: "http://...."}]
    Fiber(function() {
        var fiber = Fiber.current;
        for(var i = 0, len = feedsData.length; i < len; i++) {
            var feed = feedsData[i];
            parser.parseURL(feed.url, function(err, out) {
                console.log(feed._id, i);
                if(err) return fiber.throwInto(err);
                fiber.run();
            });
            Fiber.yield();
            console.log('here', i);
        }
        console.log('there');
    }).run();
    console.log('and there');
    

    The output will be :

    "and there"
    "1234" "0"
    "here" "0"
    "6789" "1"
    "here" "1"
    "there"
    

    Note that everything in the Fiber function is executed in its own fiber as if it was asynchrone, which is why "and there" is outputed first