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