Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic wrapper to harmonise functions to async style

I would love to write a generic wrapper that takes a function, and returns the "async-style" version of that function IF it wasn't async to start with.

Trouble is, there is no easy way to know whether the call is sync or async. So... this basically "cannot be done". Right?

(Note that the wrapper should harmonise sync functions to async style, and LEAVE async functions alone)

var wrapper = function( fn ){

    return function(){
      var args = Array.prototype.splice.call(arguments, 0);

      var cb = args[ args.length - 1 ];

      // ?!?!?!?!?
      // I cannot actually tell if `fn` is sync
      // or async, and cannot determine it!    

      console.log( fn.toString() );
    }
}

var f1Async = wrapper( function( arg, next ){
  next( null, 'async' + arg );
})

var f2Sync = wrapper( function( arg ){
  return 'sync' + arg;
})


f1Async( "some", function(err, ret ){
  console.log( ret );
});


f2Sync( "some other", function(err, ret ){
  console.log( ret );
});
like image 764
Merc Avatar asked Oct 29 '13 16:10

Merc


1 Answers

You cannot find out what the accepted arguments of a function are, so you cannot find out if it takes a callback or not.

like image 102
mtsr Avatar answered Oct 12 '22 09:10

mtsr