0101
0101

Reputation: 2712

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...
});

Upvotes: 0

Views: 125

Answers (2)

Bergi
Bergi

Reputation: 665155

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.

Upvotes: 2

major-mann
major-mann

Reputation: 2652

There is no benefit from making it "asynchronous". In fact, the code will run synchronously, with the getString method only exiting after the callback is complete.

The only decision you really have to make is one of coding style (Do you want it to seem asynchronous or not.)

function getString(arg, callback)
{
    for(var i = 0;i<100;i++)
    {
        // ...
    }
    //Callback will execute synchronously, and you will wait here until it is complete
    callback(string);
}

Upvotes: 0

Related Questions