ROCOREcoding nodejs async with generator
对函数式一窍不通? 被群蛇一样的异步回调if else搞得愁眉苦脸?
ROCORE 将会改变你的异步编程习惯. 使用ECMAScript 6在nodejs中编写顺序的异步程序.共同体验生成器和函数式思想的强大.
任务和队列将是nodejs异步编程的主题.
- yield停止当前任务
- next跳到下一个任务(如果有, 否则跳到最外部)
- ynext返回到当前任务
app.post( '/:user/ttt', function* (ynext, next, req, res) { let a = yield test(1, ynext); stack.push(a[0]); let b = yield next(ynext); stack.push(b[0][0]); let c = yield test(2, ynext); stack.push(c[0]); assert.deepEqual(stack, [ 1, 3, 5, 0, 6, 6, 4, 4, 2 ]); process.exit(0); }, function* (ynext, next, req, res) { let a = yield test(3, ynext); stack.push(a[0]); let b = yield next(ynext); stack.push(b[0][0]); let c = yield test(4, ynext); stack.push(c[0]); }, function* (ynext, next, req, res) { let a = yield test(5, ynext); stack.push(a[0]); let b = yield next(ynext); stack.push(b[0][0]); let c = yield test(6, ynext); stack.push(c[0]); } );
使用ROCORE,自由的在单个队列多个任务中切换,每一个代码片段都可以看做一个"case",只需要"if",而不再需要"else",代码变得扁平,更加的易于插拔。
let sid = req.cookie.sid; if (!sid) { res.writeHead(302, { 'location':'/login' }); res.end(); yield next(0); // 跳出任务队列 } let yctx = yield rcli.hgetall(sid, ynext); let err = yctx[0]; let user = yctx[1]; if (err) { res.writeHead(500); res.end('server error'); yield next(0); // 跳到下一任务 } if (!user) { res.writeHead(302, { 'location':'/login' }); res.end(); yield next(0); // 跳出任务队列 } req.session = user; req.session.sid = sid; yield next(); // 跳到下一任务
node -v >= 0.11.14 请使用nvm作为nodejs版本控制工具
node --harmony --use-strict server.js 启动生成器异步程序
评论