Compose

更新时间:2023-02-22 15:57:53标签:web前端

1export interface Middleware<C> {
2 (ctx: C, next: () => Promise<void>): Promise<void>;
3}
4export function compose<C>(middlewares: Middleware<C>[]) {
5 return async function(ctx: C) {
6 function dispatch(i = 0): Promise<void> {
7 const fn = middlewares[i];
8 if (i >= middlewares.length) {
9 return Promise.resolve();
10 }
11 return Promise.resolve(fn(ctx, function next() {
12 return dispatch(i + 1);
13 }));
14 }
15 await dispatch();
16 return ctx;
17 };
18}
1import { FC, useCallback } from 'react';
2import { compose } from '@shared/utils';
3
4/* eslint-disable no-console */
5const f = compose<any>([async function(ctx, next) {
6 ctx.a = 'a';
7 console.log('第一个, next之前');
8 await next();
9 console.log('第一个, next之后');
10}, async function(ctx, next) {
11 ctx.b = 'b';
12 console.log('第二个, next之前');
13 await next();
14 console.log('第二个, next之后');
15}, async function(ctx, next) {
16 ctx.c = 'c';
17 console.log('第三个, next之前');
18 await next();
19 console.log('第三个, next之后');
20}]);
21
22export const ComposeExample: FC = () => {
23
24 const test = useCallback(() => {
25 f({}).then(ctx => {
26 console.log(ctx);
27 });
28 }, []);
29
30 return (
31 <button onClick={test}>点击执行</button>
32 );
33};