简体   繁体   中英

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

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 ?

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.

According to the async readme it can be used directly in the browser. Using browersify seems excessive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM