Hey,

So async functions look like the following:

  asyncFn(param1, param2, ..., callback);

The callback should be the last argument. That means you can override an 
async function to call your pre hook before it gets executed and also 
override the callback so that the hook gets executed after the it.

For example:

  hookify = function(originalFn, preFn, afterFn) {
    var fn = originalFn;

    originalFn = function() {
      var args = Array.prototype.slice.call(arguments);

      // the callback is the last argument; we also delete it from the args 
array this way
      var originalCallback = args.pop();

      // override the callback so that it calls the after hook
      var callback = function() {
        originalCallback.apply(this, arguments); 
        afterFn();
      };

      // put in the args array again, as the last item    
      args.push(callback);

      // call the pre hook
      preFn();
            
      // execute original function
      fn.apply(this, args);
    };
  };

So then you can just use it this way:

  hookify(asyncFn, function() {
    console.log('pre hook');
  }, function() {
    console.log('post hook');
  });

  asyncFn(1, 2, 3, function() {
    console.log('callback');
  });

That should log:

  pre hook
  callback
  post hook

Note: I haven't tested that function, but that's the principle.

Let me know if that clarifies it for you.

Best,
Alex

On Saturday, October 18, 2014 3:42:47 AM UTC+3, 赵正中 wrote:
>
> Hi,
>
> I'm a Node.js newbie
>
> Can anyone show me how to write a simple javascript/Node.js hook(add pre 
> and post to (async)function)? 
> <http://stackoverflow.com/questions/26428862/can-anyone-show-me-how-to-write-a-simple-javascript-node-js-hookadd-pre-and-pos>
>
> So far, I've checked
>
> Javascript function hooks 
> <http://stackoverflow.com/questions/789630/javascript-function-hooks/789654#789654>
>
> https://github.com/cowboy/javascript-hooker
>
> https://github.com/bnoguchi/hooks-js
>
> But I have hard time to understand the code, can anyone help?
>
> Thank you!
>

-- 
Job board: http://jobs.nodejs.org/
New group rules: 
https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/nodejs/ca0ce96e-c8c9-4a0d-a655-145184b6599d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to