CNode

终于不用co了,开始使用async/await

分享
SSamurais发布于9 年前最后回复9 年前3 回复7845 浏览0 收藏

之前在项目里,使用了很多co的代码,co.wrap 看上去不是那么可读性。 同时也尝试了babel和typescript, 那种compile一次也是比较烦。

在node 7.6+中,全面支持 async/await。在项目里,我用的比较多了是基于洋葱模型的middleware - microloom

   // simulate a request.
function wait(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms || 1))
}
 
let app = require('microloom');
app.use(async function (ctx, next) {
    ctx.arr.push(1)
    await next()
    // process requests with Promise, Generator, Async or any object.
    await wait(1)
    ctx.arr.push(4)
    return ctx;
});
 
app.use(async function (ctx, next) {
    ctx.arr.push(2)
    await next()
    ctx.arr.push(3)
});
 
app.handle({ /* Inject ctx value */
    arr: [0]
}).then(function (result) {
    console.log(result);
    // { arr: [ 0, 1, 2, 3, 4 ] }
}).catch(function (e) {
    console.error(e)
});
 
查看回复

回复 (3)

E
Equim-chan#1·9 年前

koa2.x也支持了async/await 不过个人感觉效率上应该没有co高,虽然规范了点。

L
lunix01#2·9 年前

终极

参与回复
登录后即可参与回复。登录