Clone and edit this document
Runkit
Runkit
home page
user forum
new notebook
clone notebook
download notebook
support & documentation
log in
sign up
new notebook
help & feedback
clone this notebook
download this notebook
Sign In
Sign Up
before-after-hook
node v14.20.1
version:
1.0.0
endpoint
share
tweet
演示before-after-hook 的使用方法
const _ = require("lodash"); const Hook = require("before-after-hook"); let stepIndex = 0; const getNextStep = ()=> { stepIndex += 1; return `<执行步骤${stepIndex}>` } /** * Step1: 创建一个 Hook 的单一实例 */ const hook = new Hook.Singular(); /** * Step2: 模拟一个异步请求数据的函数, 返回一个 Promise对象 */ const fetchData = (options =[]) => { console.log(`${getNextStep()} - 进入fetchData 函数体`, options); return new Promise((resolve, reject) => { if (_.isArrayLike(options)) { setTimeout(() => { console.log(`${getNextStep()} - 获取到数据`) resolve([1, 2, 3, 4]); console.log(`${getNextStep()} - reslove`) }, 3000); } else if (_.isPlainObject(options)){ reject([0]) console.log(`${getNextStep()} - reject`) } else { throw new Error(`不兼容处理的值: ${options}`); } }); }; /** * Step3: 创建一个与 fetchData 建立相互关系的 Hook 绑定 */ const getDataWithHookable = (options) => { return hook(fetchData, options) .then((res) => { console.log(`${getNextStep()} - then 执行异步请求有数据返回`); console.log(`${getNextStep()} - 结果:`, res); if (_.isUndefined(res)) { throw new Error(-999) } }) .catch((err) => { console.log(`${getNextStep()} - catch 执行异步请求发生异常`, err); }); }; /** * Step4:注册 before、error、after 的 hook */ hook.before(() => { console.log(`${getNextStep()} - 调用 before hook`); }); hook.error((err) => { console.log(`${getNextStep()} - 调用 error hook`); console.error(err); }); hook.after(() => { console.log(`${getNextStep()} - 调用 after hook`); }); /** * 生成器,针对数组 */ function * asyncGeneratorForArray(array= []) { let i = 0; while (i < array.length) { yield array[i++]; } } /** * Step5: 正常调用 getDataWithHookable({}); * 会发现hook的部分,已经生效了 */ async function main() { // 根据输入不同的option值,处理结果是不一样的 const optionList = [[],{}, true]; for await (const option of asyncGeneratorForArray(optionList)) { stepIndex = 0; await getDataWithHookable(option); console.log("-------------------"); } } main();
Loading…
no comments
sign in
to comment