Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

koa-compose #132

Open
hoperyy opened this issue Feb 13, 2019 · 0 comments
Open

koa-compose #132

hoperyy opened this issue Feb 13, 2019 · 0 comments

Comments

@hoperyy
Copy link
Owner

hoperyy commented Feb 13, 2019

image

  • compose 接收 middlewares,返回一个 thenable 对象,可以理解为 promise1

  • promsie1 的状态取决于 middleware 1 的状态,

    middleware 1 的状态取决于其 next 的返回值状态,也就是 middleware 2 的状态,

    middleware 2 本身返回一个 promsie,但为了自动执行,下面代码中,next 返回了递归的 dispatch,也就是 middleware 2 等外面又包了一层 promise

  • 处理下错误和 middleware 执行完的情况

function compose(middlewares) {
    let index = 0;
    const dispatch = (context) => {
        const fn = middlewares[index];

        if (!fn) {
            return Promise.resolve();
        }

        try {
            return Promise.resolve(fn(context, () => {
                index++;
                return dispatch(context);
            }));
        } catch(err) {
            return Promise.reject(err);
        }
    };

    return function(context) {
        return dispatch(context);
    };
}

const delay = (time = 1000) => {
    return new Promise(resolve => setTimeout(resolve, time));
};

const m1 = async (context, next) => {
    await delay();
    console.log(1);
    await next();
};

const m2 = async (context, next) => {
    await delay();
    console.log(2);
    await next();
};

const m3 = async (context, next) => {
    await delay();
    console.log(3);
    await delay();
    await next();
};

const run = compose([ m1, m2, m3 ]);

run({}).then(() => {
    console.log('done');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant