新特性的發(fā)布
最近nodejs發(fā)布了v7.6.0。這個版本,正式包含了 async和await的用法,再也無需使用harmony模式或者使用babel轉換了。
koa2
然后發(fā)現(xiàn)koa官方也隨即更新了github上的源碼。
Koa is not bundled with any middleware.
Koa requires node v7.6.0 or higher for ES2015 and async function support.
這也宣告,koa2的時代正是來臨。
中間件的寫法
官方文檔上寫著有三種
- common function
- async function
- generator function
async(node v7.6+)
app.use(async (ctx, next) => {
const start = new Date();
await next();
const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
上面這種模式需要將node版本升級到v7.6或者更高。
common
app.use((ctx, next) => {
const start = new Date();
return next().then(() => {
const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
});
這種模式下,無需使用async和await特性,只是一個普通函數(shù)。在koa2中間件里面,next()返回的是一個promise。
generator
app.use(co.wrap(function *(ctx, next) {
const start = new Date();
yield next();
const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
}));
在koa1的時代,所有的中間件都是一個generator函數(shù)。來到koa2就不是了,當然,也可以采用generator的寫法。只是需要使用一個包裝器,如 co 。
平滑升級
如果原有項目是基于koa1,那么,如果想要平滑過渡到koa2而不想要改動太多,那么就需要模塊koa-convert了。具體用法
const convert = require('koa-convert');
app.use(convert(function *(next) {
const start = new Date();
yield next;
const ms = new Date() - start;
console.log(`${this.method} ${this.url} - ${ms}ms`);
}));
該模塊會轉化成koa2所需要的東西。
例子
既然發(fā)布了終極解決方案,那么,我也會優(yōu)先并且傾向于這種寫法。下面是我嘗試寫的一個具有參考意義但不具有實際意義的中間件。
中間件一般來說都放在另外一個文件。一來不顯臃腫,而來,模塊化嘛。
index.js
const Koa = require('koa');
const app = new Koa();
const time = require('./time');
app.use(async time());
// response
app.use(ctx => {
ctx.body = 'Hello Koa';
});
app.listen(3000);
time.js
function time(options) {
return function (ctx, next) {
console.time(ctx.req.url);
ctx.res.once('finish', function () {
console.timeEnd(ctx.req.url);
});
await next();
}
}
module.exports = time;
然后運行了一下,發(fā)現(xiàn)報錯了。。。說我缺少)

為啥會錯呢?難道不能將async和await拆開來寫???那我改改。
index.js
app.use(time());
time.js
function time(options) {
return async function (ctx, next) {
console.time(ctx.req.url);
ctx.res.once('finish', function () {
console.timeEnd(ctx.req.url);
});
await next();
}
}
好的,大功告成。將async關鍵字挪到中間件聲明的地方即可。所以一個正確地中間件是這么聲明的
app.use(中間件);
// 中間件:
async function (ctx, next) {
await next();
})
總結
我太年輕了,以為我想的就是別人想的。
- async和普通函數(shù)合在一起使用的。就和當初的generator一樣,不能將function關鍵字和
*分開。 - 這個新特性不只是在koa2才能發(fā)揮作用,在平時的express app也能使用。
- async/await:一個將異步寫成同步語法的終極解決方案,解決可怕的callback hell。
再也不用 promise.then().then()....then()的丑陋寫法了,直接是
let a1 = await p1();
let a1 = await p1();
.....
let an = await pn();
不錯