koajs / compose

Middleware composition utility

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Why use Promise.resolve() to wrap the execution results of each middleware?

zh-lx opened this issue · comments

In the following code, why use Promise.resolve() to wrap the execution results of each middleware?

try {
  return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
} 

I think it is enough to use Promise.resolve() to wrap dispatch(0) and return the rest of middleware execution results directly. Just like the following code:

return function (context, next) {
    // last called middleware #
    let index = -1
-   return dispatch(0)
+   return Promise.resolve(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, dispatch.bind(null, i + 1)));
+       return fn(context, dispatch.bind(null, i + 1));
      } catch (err) {
        return Promise.reject(err)
      }
    }
  }

Could you help me to answer this question, please!

commented

Use this use case to test.
i think The point is to support next().then()

    function fn1(ctx, next) {
      console.log(1)
      next().then(()=>{
        console.log(2)
      })
    }
    function fn2(ctx, next) {
      console.log(3)
      next().then(()=>{
        console.log(4)
      })
    }

correct, this ensures that the result is always a promise