Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript node.js中函数的挂钩_Javascript_Node.js - Fatal编程技术网

Javascript node.js中函数的挂钩

Javascript node.js中函数的挂钩,javascript,node.js,Javascript,Node.js,如何在函数上应用钩子。我想在函数上应用前后钩子,以便在调用该函数时触发这些钩子。我见过express.js的中间件概念,但它只适用于路由,不适用于函数,因为它用于路由处理。我需要为我的函数使用相同类型的钩子,所以无论何时在钩子前后在服务器端调用我的函数,钩子都会触发 function main(){ console.log("When ever this function is called as myfun()"); } function after(){ console.log(

如何在函数上应用钩子。我想在函数上应用前后钩子,以便在调用该函数时触发这些钩子。我见过express.js的中间件概念,但它只适用于路由,不适用于函数,因为它用于路由处理。我需要为我的函数使用相同类型的钩子,所以无论何时在钩子前后在服务器端调用我的函数,钩子都会触发

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

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

您可以使用一种函数组合/链接模式:

例如:

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();

你能举个例子吗。为什么不简单地包装函数?@davintroon Eidt举个例子