handle async flow/errors of profile update

This commit is contained in:
Berkeley Martinez
2015-03-17 21:09:54 -07:00
parent ab14b32d19
commit 3b913be893
2 changed files with 34 additions and 15 deletions

View File

@ -1,4 +1,5 @@
var User = require('../models/User'), var async = require('async'),
User = require('../models/User'),
Challenge = require('./../models/Challenge'), Challenge = require('./../models/Challenge'),
Bonfire = require('./../models/Bonfire'), Bonfire = require('./../models/Bonfire'),
Story = require('./../models/Story'), Story = require('./../models/Story'),
@ -303,7 +304,7 @@ module.exports = {
}); });
})(); })();
}, },
updateUserStoryPictures: function(userId, picture, username) { updateUserStoryPictures: function(userId, picture, username, cb) {
var counter = 0, var counter = 0,
foundStories, foundStories,
@ -311,7 +312,7 @@ module.exports = {
Story.find({'author.userId': userId}, function(err, stories) { Story.find({'author.userId': userId}, function(err, stories) {
if (err) { if (err) {
throw err; return cb(err);
} }
foundStories = stories; foundStories = stories;
counter++; counter++;
@ -319,7 +320,7 @@ module.exports = {
}); });
Comment.find({'author.userId': userId}, function(err, comments) { Comment.find({'author.userId': userId}, function(err, comments) {
if (err) { if (err) {
throw err; return cb(err);
} }
foundComments = comments; foundComments = comments;
counter++; counter++;
@ -330,19 +331,28 @@ module.exports = {
if (counter !== 2) { if (counter !== 2) {
return; return;
} }
var tasks = [];
R.forEach(function(comment) { R.forEach(function(comment) {
comment.author.picture = picture; comment.author.picture = picture;
comment.author.username = username; comment.author.username = username;
comment.markModified('author'); comment.markModified('author');
comment.save(); tasks.push(function(cb) {
comment.save(cb);
});
}, foundComments); }, foundComments);
R.forEach(function(story) { R.forEach(function(story) {
story.author.picture = picture; story.author.picture = picture;
story.author.username = username; story.author.username = username;
story.markModified('author'); story.markModified('author');
story.save(); tasks.push(function(cb) {
story.save(cb);
});
}, foundStories); }, foundStories);
async.parallel(tasks, function(err) {
if (err) { return cb(err); }
cb();
});
} }
} }
}; };

View File

@ -377,9 +377,18 @@ exports.postUpdateProfile = function(req, res, next) {
if (err) { if (err) {
return next(err); return next(err);
} }
req.flash('success', {msg: 'Profile information updated.'}); resources.updateUserStoryPictures(
res.redirect('/account'); user._id.toString(),
resources.updateUserStoryPictures(user._id.toString(), user.profile.picture, user.profile.username); user.profile.picture,
user.profile.username,
function(err) {
if (err) { return next(err); }
req.flash('success', {
msg: 'Profile information updated.'
});
res.redirect('/account');
}
);
}); });
}); });
}); });