# waterfall-unitwork **Repository Path**: fanjinde/waterfall-unitwork ## Basic Information - **Project Name**: waterfall-unitwork - **Description**: 通过ctx控制函数的执行与否,工作性质类似vue-router的hook,或者middleware - **Primary Language**: TypeScript - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-01-27 - **Last Updated**: 2023-01-31 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 介绍 工作性质类似middleware,具有上下文的特性 ## 使用场景 1. 串联请求 2. 按流程处理业务 ## 代码使用 ```typescript // 串联请求 import WaterfallUnitWork from 'waterfall-unitwork'; // 明确上下文数据 type Data = { deptId?: string; users?: [] } const tandemRequest = new WaterfallUnitWork({}) tandemRequest .add((ctx) => { // 请求部门 复制 fetch('getDepeId').then((res) => { if (res.code === 200) { ctx.data.deptId = res.deptId // flag为true,代表进入下一个函数 ctx.next(true) } else { // ctx为false,代表进入end函数 // 错误信息也可以定义在ctx.data上 ctx.next(false) } }) }) .add((ctx) => { console.log('ctx.data.deptId', ctx.data.deptId) // 根据ctx.data.deptId请求人员 }) .end((flag, ctx) => { // 根据flag判断是否业务处理成功 }) ``` ```typescript // 根据进入微信小程序后解析的路径判断不同的业务 import WaterfallUnitWork from 'waterfall-unitwork'; import type {UnitWorkFn} from 'waterfall-unitwork' /** * 登录节点 * 判断是否登录 * 类似的方法可重复声明,而后重复使用 */ const loginNode: UnitWorkFn> = (ctx) => { // 判断是否登录 if (hasLogin()) { ctx.next(true) } else { // 1. 登录 // 进行下一个节点 ctx.next(true) } } // task1需要登录 const task1 = new WaterfallUnitWork>({}) // task2 需要登录 const task2 = new WaterfallUnitWork>({}) task1 .add(loginNode) .add((ctx) => { // 其他业务 }) .end((flag, ctx) => { // 处理最终 }) task2 .add((ctx) => { // 业务1 }) .add((ctx) => { // 业务2 }) .end((falg, ctx) => { // 最终业务 }) ```