1

Both seem to be doing the same thing, i.e. calculating f(g(h(x))), when called like this async.compose(f, g, h) or _.compose(f, g, h).

Is there any difference between the two calls ?

2 Answers 2

3

As its name implies, async.compose composes asynchronous functions.

It gets the result via callback parameter, not return value.

2
  • So which of these is the preferred one and under which scenarios ? Aug 26, 2013 at 17:39
  • 1
    @ChintanPathak: You need to understand what async means.
    – SLaks
    Aug 26, 2013 at 17:53
1

I faced same situation where I needed one function I got from some lib to use the return value from async.compose() call. So I did wonder: How can one get the return value from async.compose()?
If you write:

var gotFromAsyncCompose = async.compose(
  function(gotParam, callback) {
    callback(null, 'hi ' + gotParam + '!';
  },
  function(name, callback) {
    callback(null, name.toUpperCase());
  }
);
var returnValue = gotFromAsyncCompose('moe', function(err, result){
  return result;
});
console.log(returnValue);

You'll get undefined as the value of returnValue.
So, async.compose() always return undefined as return value even if the last executed statement is return 'A';. You'll still get undefined!

When it comes to _.compose(), I tried the same:

var w = _.compose(
  function(name){
    return 'hi '+name;
  },
  function(got){
    return got.toUpperCase() +'!';
  });
);
var returnValue = w('moe');
console.log(returnValue);

This time, you get 'hi MOE!' as expected as the value of returnValue. You don't get undefined like the behaviour of async.compose().

I didn't wrote any of these compose functions, but it seems that the difference between the two seems to be that async.compose() won't return any value whereas _.compose() will return the value you pass to return within the last executed function.
But, there is another difference: _.compose() doesn't take care of any asynchronous call you make inside your functions. You have to write only synchronous code within all the functions that comprise your _.compose().

The four main differences I can see as of April 28th 2014 are:

  • async.compose() does not return a value
  • async.compose() does take care of asynchronous calls within functions
  • _.compose() does return a value
  • _.compose() does not take care of asynchronous calls within functions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.