0101 0101 - 7 months ago 10
Javascript Question

Should be a function containing loop asynchronous in NodeJS?

I am not sure how to create (declare) the following function. The function contains only a for loop which generates a string. There aren't any "heavy" calculations done. It is pretty simple and fast.

function getString(arg) {
for (var i = 0; i<100; i++) {
// ...
}

return string;
}

var string = getString(arg);
// ... an async code which will use the string


Or shall I make it async? So it would look like this:

function getString(arg, callback) {
for (var i = 0; i<100; i++) {
// ...
}

callback(string);
}

getString(arg, function(res) {
// Async code...
});

Answer

Or should I make it async? So something like this:

function getString(arg, callback) {
    for(var i = 0;i<100;i++) {
        // ...
    }
    callback(string);
}

No. That code does still run synchronousls, only with an odd callback style for returning the result. Since JS does no tail call optimisation or has continuation support, it just introduces the pyramid of doom without any benefit.

Do not use this unless you really make it asynchronous (setTimeout, nextTick etc), for example to defer the single loop iterations.