终于不用co了,开始使用async/await - CNode技术社区

终于不用co了,开始使用async/await
发布于 9 年前 作者 Samurais 7579 次浏览 来自 分享

之前在项目里,使用了很多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 回复

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

回到顶部

AltStyle によって変換されたページ (->オリジナル) /