koa的中间件compose

用到的知识点:

1、bind函数

2、函数递归调用自身

3、promise

'use strict'

/**
 * Expose compositor.
 */

module.exports = compose

/**
 * Compose `middleware` returning
 * a fully valid middleware comprised
 * of all those which are passed.
 *
 * @param {Array} middleware
 * @return {Function}
 * @api public
 */

function compose (middleware) {
  if (!Array.isArray(middleware)) throw new 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!')
  }

  /**
   * @param {Object} context
   * @return {Promise}
   * @api public
   */

  return function (context, next) {
    // last called middleware #
    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]
      console.log(fn)
      if (i === middleware.length) fn = next
      if (!fn) return Promise.resolve()
      try {
        return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
      } catch (err) {
        return Promise.reject(err)
      }
    }
  }
}

  test

function one(ctx,next){
    console.log('第一个');
    var d=2
    next().then(function(ct){
        console.log(ct)
        d=222
    })
    console.log(d)
    return 21
}
function two(ctx,next){
    console.log('第二个');
    return next();
}
function three(ctx,next){
    console.log('第三个');
    return 'three';
}
// 传入中间件函数组成的数组队列,合并成一个中间件函数
const middlewares = compose([one, two, three]);
// 执行中间件函数,函数执行后返回的是Promise对象
middlewares().then(function (result){
    console.log('队列执行完毕',result);    
})

  

posted @ 2018-11-16 16:12  无工时代  阅读(743)  评论(0编辑  收藏  举报