javascript - Node.js and asynchronous programming with Q -
is following correct way go things? sign controller action. im creating user , group add user to. notice have method level variables called user , group. rest of code asynchronous using q module.
is ok have method level variables or overriden person signing @ same time?
exports.postsignup = function(req, res, next) { var user, group; return q.invoke(exports, 'parseuser', req, null) .then(function(u) { user = u; return q.invoke(exports, 'postcreateuser', user).fail(function(err) { throw err; }); }) .then(function() { group = new group(); group.userids = [user._id]; return q.invoke(exports, 'postcreategroup', group).fail(function(err) { throw err; }); }) .then(function() { user.groupid = group._id; group.userids = [ user._id ]; }) .then(function() { return q.ninvoke(req, 'login', user).fail(function(err) { throw err; }); }) .then(function() { return res.redirect('/tour'); }) .fail(function (err) { console.log('u:' + user); console.log('g:' + group); return exports.createvalidationerror(error, req, res, user); }); };
is ok have method level variables or overriden person signing @ same time?
no, won't locally scoped postsignup
function.
it little ugly, nesting them might better choice here:
exports.postsignup = function(req, res, next) { return q.invoke(exports, 'parseuser', req, null).then(function(user) { return q.invoke(exports, 'postcreateuser', user).then(function(createduser) { var group = new group(); group.userids = [user._id]; return q.invoke(exports, 'postcreategroup', group).then(function(createdgroup) { user.groupid = group._id; group.userids = [ user._id ]; // repeat this? return q.ninvoke(req, 'login', user) }).then(function(loggedinuser) { return res.redirect('/tour'); }).fail(function(err) { console.log('g:' + group); throw err; }); }).fail(function(err) { console.log('u:' + user); return exports.createvalidationerror(error, req, res, user); }); }) // .fail(function(err) { // … // parseuser or createvalidationerror failed // }); };
do need break down different steps different functions or can have 1 async function?
you have 1 async function currently, might want break down creating user new group, , logging him in plus redirecting him /tour
.
Comments
Post a Comment