5

before-after-hook钩子函数 - nd

 1 year ago
source link: https://www.cnblogs.com/tylerdonet/p/16984747.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

before-after-hook

最近看别人的代码,接触到一个插件,before-after-hook,百度搜一圈也没有看到什么地方有教程,看这个字面意思是一个hook,和axios里面的拦截器,vue-router里面的导航守卫类似。插件名字暂且叫它“前后钩子”吧,本文简单介绍这个插件的使用方法。

1.单独的钩子

先看一个简单的例子,代码如下:

  import Hook from 'before-after-hook'
  const hook = new Hook.Singular()

  function getData(options) {
    const result = hook(fetchData, options)
  }
  //设置钩子
  hook.before(beforHook)
  hook.error(errorHook)
  hook.after(afterHook)
  getData({id: 123})

  function fetchData(options) {
    console.log('fetchData', options)
    return options
  }

  function handleData(res) {
  }
  function handleGetError(e) {
  }
  function beforHook(e) {
    console.log('beforHook', e)
  }
  function errorHook(e) {
    console.log('errorHook', e)
  }
  function afterHook(e) {
    console.log('afterHook', e)
  }

输出结果如下图1:

image

从结果可以看出,在执行fetchData方法的时候,先去执行beforeHook,执行完fetchData语句的时候,又执行了afterHook。如果在执行fetchData的时候抛出一个错误,会触发errorHook,只需在上面的fetchData方法中抛出一个错误,代码如下:

    console.log('getData', options)
    throw new Error('error')
    return options
  }

执行结果如下图2:

image

从执行结果上可以看到当fetchData方法报错的时候会触发errorHook。

before-after-hook简单用法就是先用钩子钩住一个方法,然后再设置这个钩子的处理函数:beforeHook,errorHook,afterHook,对应的在这个方法调用之前,调用出错,调用之后触发相应的钩子函数。

2.Hook collection

Hook.Colleciton和Hook.Singuar本质上没有什么不同,Hook.Collection创建的钩子来处理一些有相同的名称的钩子。对于这两种钩子,他们的执行顺序如下:

  1. beforeHook
  2. fecchFromDatabase
  3. afterHook
  4. handleData

来看下面的代码

  import Hook from 'before-after-hook'
  const hookCollection = new Hook.Collection()

  function getData(options) {
    try {
      hookCollection('get', fetchData, options)
      handleData(options)
    } catch (e) {
      handleGetError(e)
    }
  }
  hookCollection.before('get', beforHook)
  hookCollection.error('get', errorHook)
  hookCollection.after('get', afterHook)
  getData({id: 123})


  function fetchData(options) {
    console.log('getData', options)
    return options
  }
  function beforHook(e) {
    console.log('beforHook', e)
  }
  function errorHook(e) {
    console.log('errorHook', e)
  }
  function afterHook(e) {
    console.log('afterHook', e)
  }

  function handleData(data) {
    console.log('handleData', data)
  }

  function handleGetError(e) {
    console.log('handleGetError', e)
  }

输出结果如下图3:

image

beforeHook可以在将请求参数传递给fetchDatabase的时候修改传入的参数。
在beforeHook和fetchFromDatabase的时候如果有错误,触发errorHook。
如果再afterHook里出现错误,会调用handleGetError,而不是afterHook,handleData。
注意他们的名字必须一致,不然会执行不到。

参考文档:https://www.npmjs.com/package/before-after-hook


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK