compose icon indicating copy to clipboard operation
compose copied to clipboard

Abnormal middleware errors occurred and KOA could not catch error events. How about the following changes

Open LmonZero opened this issue 3 years ago • 1 comments

function compose (middleware) {
    if(!Array.isArray(middleware)) throw TypeError('Middleware stack must be an array!')
    for (const fn of middleware) {
        if(typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
    }

    let index = -1 //
    
      /**
   * @param {Object} context
   * @return {Promise}
   * @api compose
   */
    return function (context, next) {
        return new Promise((resolve, reject) => {
            function dispatch (i) { //
                if (i <= index) {
                    console.warn('[warn]next() called multiple times')
                    return //reject(new Error('next() called multiple times'))  
                } 
            
                index=i
                let fn=middleware[i]
                if(i===middleware.length) fn=next //
                if(!fn) return resolve()
    
                try {
                    return resolve(fn(context,dispatch.bind(null,i+1)))
                } catch (error) {
                    return reject(error)
                }
    
            }
            dispatch(0)
        })

    }

}

LmonZero avatar May 10 '22 05:05 LmonZero

do you have an example of an issue you're seeing? I can't tell what your code is solving

jonathanong avatar May 25 '25 20:05 jonathanong