鍍金池/ 問(wèn)答/HTML/ koa2 中間件問(wèn)題

koa2 中間件問(wèn)題

不要意思沒(méi)怎么研究過(guò)node和koa做回伸手黨,我有a.js b.js兩個(gè)文件,我想在b定義一個(gè)中間件,在a中引用它應(yīng)該怎么做?

a內(nèi)容大概如下

const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next)=> {
    let start = Date.now();
    await next();
    let end = Date.now() - start;
    console.log(end)
})

現(xiàn)在我想在b中寫(xiě)一個(gè)延遲函數(shù),怎么讓它可以在a中使用

module.exports = function() {
     setTimeout(()=> {
         ctx.body = "aaaaaa"
     },2000)
}
回答
編輯回答
離觴

搜了一下實(shí)現(xiàn)很簡(jiǎn)單返回一個(gè)async函數(shù)就好了

function log( ctx ) {
    console.log( 'ctx.method, ctx.header.host + ctx.url' )
}
module.exports = function () {
    return async function ( ctx, next ) {
      log(ctx);
      await next()
    }
  }
2017年5月18日 02:02