koajs / compose

Middleware composition utility

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

I can't catch the error ~

cavacn opened this issue · comments

const compose = require('koa-compose');

const middleware = [
    function(ctx,next){
        ctx.step1 = true;
        next();
    },
    function(ctx,next){
        ctx.step2 = true;
        next();
    },
    function(ctx,next){
        ctx.step3 = true;
        a = b;
        next();
    }
];

const ctx = {};

compose(middleware)(ctx).then(console.log).catch(console.error);

I can't catch the error ~

You have to either await or return next(). In this case it looks like you should return since middleware don't do anything after calling next

OK , I change my example code ~

const compose = require('koa-compose');

const middleware = [
    function (ctx, next) {
        // ctx.step1 = true;
        ctx.steps = [];
        ctx.steps.push(1);
        return next();
    },
    function (ctx, next) {
        next();
        ctx.steps.push(4);
    },
    function (ctx, next) {
        next();
        a = b;
        ctx.steps.push(3);
    },
    function (ctx, next) {
        next();
        ctx.steps.push(2);
    }
];

const ctx = {};

compose(middleware)(ctx).then(() => {
    console.log('success', ctx);
}).catch((err) => {
    console.log('err', err.stack);
});

If I either return next(), it seems Unreasonable~

No exception is going to be thrown with the code above as far as I can tell so the catch at the end won't be called.

However, the middleware need to return next() for the execution to go down the stack. Middleware are work like a chain of promises. A call to next() returns a promise that will resolve when the execution has gone down the stack and back up to the given middleware's position again. If you don't return the promise, the stack is traversed in reverse from that point and won't wait for the rest of the chain.

Yes , I try to change compose core code~ like this

return function (context, next) {
    let index = -1
    return dispatch(0)
    function dispatch (i) {
      if (i <= index) return Promise.reject(new Error('next() called multiple times'))
      index = i
      let fn = middleware[i]
      if (i === middleware.length) fn = next
      if (!fn) return Promise.resolve()
      try {
        // return Promise.resolve(fn(context, function next () {
          // return dispatch(i + 1)
        // }))
	return new Promise((resolve,reject)=>{
	  fn(context,()=>{resolve(dispatch(i+1));});
	})
      } catch (err) {
        return Promise.reject(err)
      }
    }
  }

I try to keep the promise chain, but can't pass npm test

@cavacn You need to return promise in all middleware calling next(). That's the design of it. Not sure why you're working against it? What are you trying to solve?

@fl0w @danwkennedy thanks, Ok , I got it ~