简体   繁体   中英

Hooks on function in node.js

How to apply hook on function.I want to apply before and after hook on a function, so that whenever that function is called those hooks will trigger.I have seen middleware concept of express.js but that work only for a route not for a function because it is for route handling. I need a same kind of hooks for my function so whenever my function is called on a server side before and after hook will trigger.

function main(){    console.log("When ever this function is called as myfun()"); }

function after(){
  console.log("called afer when ever manin is called");
}

You can use a kind of function composition/chaining pattern:

Example:

function chain() {
  const fns = Array.prototype.slice.call(arguments);

  return function (result) {
    return fns.reduce((result, fn) => fn.call(this, result), result);
  };
};

chained = chain(before, main, after);
chained();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM