Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js flow control

Node.js flow control

Problem

My question is the following: I want to return the result returned by the callback.

exports.process_logs = function(file, process_func, process_parsedLog) {
var logs = [];
var log = null;
var counter = 0;
fs.readFile(file, 'utf8', function(read_error, content) {
    if (read_error) return sys.error(read_error);

    // TODO:: Remove these hardcode rails filters
    // switch filters and split functions to a nested helper in process func
    content.split(/Processing /).forEach(function(msg, index) {
        if ((tmp = process_func(msg, index)))
            logs.push(tmp);
    });
    log = process_parsedLog(logs);
});
console.log(log);
return log;

};

But the variable "log" still null, although when I check it with console.log(log) just after "log = process_parsedLog(logs);" gives the correct result.

Problem courtesy of: morfioce

Solution

The problem is that fs.readFile is an asynchronous function and the process_logs function finishes its execution before readFile invokes the callback you passed to it. You should use promises for these situations: https://github.com/kriskowal/q

exports.process_logs = function(file, process_func, process_parsedLog) {
    var deferred = Q.defer();
    var logs = [];
    var log = null;
    var counter = 0;
    fs.readFile(file, 'utf8', function(read_error, content) {
        if (read_error) deferred.reject(sys.error(read_error));

        // TODO:: Remove these hardcode rails filters
        // switch filters and split functions to a nested helper in process func
        content.split(/Processing /).forEach(function(msg, index) {
        if ((tmp = process_func(msg, index)))
            logs.push(tmp);
        });
        log = process_parsedLog(logs);
        deferred.resolve(log);
    });
    // the result is not available yet
    return deferred.promise;
};
Solution courtesy of: Daniel Uzunu

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js flow control

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×