Can anyone show me how to write a simple javascript/Node.js hook(add pre and post to (async)function)?

57 views
Skip to first unread message

赵正中

unread,
Oct 17, 2014, 8:42:47 PM10/17/14
to nod...@googlegroups.com

alessioalex

unread,
Oct 20, 2014, 3:34:21 AM10/20/14
to nod...@googlegroups.com
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
Reply all
Reply to author
Forward
0 new messages