0101 0101 - 3 months ago 8
Javascript Question

Should a function containing loop be async in NodeJS?

I am new to NodeJS and I am not really sure how should the following function be declared. The function contains only a for loop which generates a string. There are no "heavy-weight" calculations done.

Variant 1:

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

return string;
}

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


Variant 2: Or should I make it async (async-style)? It would look something like this:

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

callback(string);
}

getRandomString(arg, function(randomString) {
// 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.