2017-03-01 62 views
2

为什么我们做这个为什么我们在使用koa路由器时等待下一次?

router.get('/data', async (ctx, next) => { 
    ctx.body = dummyjson.parse(data); 
    await next(); 
}); 

router.get('/data/:x', async (ctx, next) => { 
    const newData = dataRepeat.replace('%(x)', ctx.params.x); 
    ctx.body = dummyjson.parse(newData); 
    await next(); 
}); 

什么用的await next()

它的工作而没有就好。类似的事情预计与koa 1. yield next被添加在路由器的末尾。

+0

[这个答案](http://stackoverflow.com/questions/10695629/what-is-the-parameter-next-used-for-in-express)是快递,不兴亚但其基本上是相同的推理。 – saadq

回答

1

我会试着用一个非常笑着例子来解释一下:

const Koa = require('koa'); 
const app = new Koa(); 

// middleware 
app.use(async function (ctx, next) { 
    console.log(1) 
    await next(); 
    console.log(3) 
}); 

// response 
app.use(ctx => { 
    console.log(2) 
}); 

app.listen(3000); 

如果你在浏览器中调用localhost:3000,下面会发生在你的应用程序:

  • 第一app.use那你在这里开除的是middleware。因此,请求流首先进入该控制台,并将日志1记录到控制台。
  • 然后,当你看到这个await next()时,它下游到下一个use
  • 这里我们只是将2登录到控制台。当这完成时(并且在第二个use中没有再看到下一个,则流程返回到第一个女巫实际等待的时间,直到第二个完成。直到第二个完成。
  • 这里我们继续记录3到控制台。

希望这使得它更加清楚一点。

0

不,这是没有必要的。这是取决于你的需求。 当你调用next中间件使用next()函数。

Chec k您的路由器模块及其版本。我有使用koa路由器模块,其版本是7.2.0路由。它自己处理下一个等待。

'use strict'; 

const Koa = require('koa'), 
    router = require('koa-router'), 
    app = new Koa(); 

let pubRouter = new router(); 
let securedRouter = new router(); 

let mapper = require('./mapper'), 

// assign router to corresponding function 
mapper(pubRouter, securedRouter); 

app .use(logger(config.app.log))  
.use(bodyParser()) 
.use(pubRouter.routes()).use(pubRouter.allowedMethods()) 
    .use(jwt({ 
     secret: publicKey, 
     algorithms: ['RS256'] 
    })) 
    .use(async(ctx, next) => { 
     console.log('\n\n\n\n\n', ctx.state.user); 
     await next(); 
    }) 
    .use(securedRouter.routes()).use(securedRouter.allowedMethods()) 
    .use(async(ctx, next) => { 
     ctx.body = 'Invalid URL!!!'; 
    }); 

app.listen(port,() => console.log(`Server listening on port: ${port}`)); 
相关问题