async icon indicating copy to clipboard operation
async copied to clipboard

wish: allow this binding as a parameter

Open robludwig opened this issue 11 years ago • 2 comments

Lodash has a very helpful feature where users can pass in a parameter to functions that use an iterator, and the iterator will be bound to that context when invoked. See, for example, the parameters for their version of map. This would be very helpful for async code, as a common code pattern is to have to prepare for calling async by binding several functions, as in this example code that prepares some data on an object and then generates a report:

var prepareUserNames = report._prepareNames.bind(report);
var prepareUserPhotos = report._preparePhotos.bind(report);
var finalizeReport = report.finalize.bind(report);
async.series([prepareUserNames, prepareUserPhotos], finalizeReport);

Which could be more easily written if async had lodash-style bindings as async.series([report._prepareNames, report._preparePhotos], finalizeReport, report); with async performing the binding functions for me.

This seems to be an elegant solution to what appears to be a common mistake when using the library (judging by the binding section of the readme),

robludwig avatar Sep 14 '15 18:09 robludwig

It was a deliberate design decision to leave thisArg binding to the user, and keep it out of async.

If binding becomes a pain point, you can investigate using something like _.bindAll in your object's constructor to pre-bind any methods that are passed to async.

aearly avatar Sep 14 '15 19:09 aearly

Thanks for the suggestion, I had overlooked _.bindAll to reduce the above down to 2 lines.

I'd vote the other way on leaving bindings to the user, but I understand the decision to allow flexibility. Thanks again!

robludwig avatar Sep 14 '15 19:09 robludwig