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

Front-end: underscore.js or async.js via browserify?

Front-end: underscore.js or async.js via browserify?

Problem

So if you're a back-end node.js dev, you'll know about the awesome lib called async .

If you're a front-end dev, you'll know about the awesome lib called underscore.


Now the thing is, both of these libs tend to provide similar features to some extent.

So the question is, does it make sense to use async on the front end using browserify ?

Problem courtesy of: tUrG0n

Solution

Underscore is a utility library that provides some useful functions like each, map and reduce. But, all of these work synchronously. For example

var results = _.map([1,2,3], function(value, index, list) {
  return value * 2;
});

console.log(results);

Output: [2, 4, 6]

If you notice, the console.log(results) statement gets called only after the _.map() function is fully executed and the results returned. This is the typical synchronous style of programming that you use in browser scripting.

On the server, where Node.js is the king, synchronous programming as above is harmful to the event loop. There, asynchronous style of programming is preferred. Take a look at the same map method using the async library.

async.map([1,2,3],
        function mapper(item, callback) {
            callback(null, item * 2);
        },
        function(error, results) {
            console.log(results);
        }
);

Output: [2, 4, 6]

If you notice, it doesn't return the mapped array as return value, instead the mapped array is passed to the callback function and the console.log(results) is used to print the results inside of the callback.

One side effect of this style of programming is that the iterator function gets called in parallel, not in serial order thereby enabling way more scalability if the iterator function uses any I/O.

So, even though some of the functions offered by async library is similar to the one's offered by Underscore, they are for different purposes as demonstrated above. Now, the decision of which ones to use depends on your application requriements and programming style.

Solution courtesy of: Ganeshji Marwaha

Discussion

View additional discussion.



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

Share the post

Front-end: underscore.js or async.js via browserify?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×