From 3b913be893b5621d783176dd081cc2fc34e41e6b Mon Sep 17 00:00:00 2001 From: Berkeley Martinez Date: Tue, 17 Mar 2015 21:09:54 -0700 Subject: [PATCH] handle async flow/errors of profile update --- controllers/resources.js | 34 ++++++++++++++++++++++------------ controllers/user.js | 15 ++++++++++++--- 2 files changed, 34 insertions(+), 15 deletions(-) diff --git a/controllers/resources.js b/controllers/resources.js index 9a05a04706..dd6994a3ff 100644 --- a/controllers/resources.js +++ b/controllers/resources.js @@ -1,4 +1,5 @@ -var User = require('../models/User'), +var async = require('async'), + User = require('../models/User'), Challenge = require('./../models/Challenge'), Bonfire = require('./../models/Bonfire'), Story = require('./../models/Story'), @@ -303,7 +304,7 @@ module.exports = { }); })(); }, - updateUserStoryPictures: function(userId, picture, username) { + updateUserStoryPictures: function(userId, picture, username, cb) { var counter = 0, foundStories, @@ -311,7 +312,7 @@ module.exports = { Story.find({'author.userId': userId}, function(err, stories) { if (err) { - throw err; + return cb(err); } foundStories = stories; counter++; @@ -319,7 +320,7 @@ module.exports = { }); Comment.find({'author.userId': userId}, function(err, comments) { if (err) { - throw err; + return cb(err); } foundComments = comments; counter++; @@ -330,19 +331,28 @@ module.exports = { if (counter !== 2) { return; } + var tasks = []; R.forEach(function(comment) { - comment.author.picture = picture; - comment.author.username = username; - comment.markModified('author'); - comment.save(); + comment.author.picture = picture; + comment.author.username = username; + comment.markModified('author'); + tasks.push(function(cb) { + comment.save(cb); + }); }, foundComments); R.forEach(function(story) { - story.author.picture = picture; - story.author.username = username; - story.markModified('author'); - story.save(); + story.author.picture = picture; + story.author.username = username; + story.markModified('author'); + tasks.push(function(cb) { + story.save(cb); + }); }, foundStories); + async.parallel(tasks, function(err) { + if (err) { return cb(err); } + cb(); + }); } } }; diff --git a/controllers/user.js b/controllers/user.js index 7648e80441..bb63ceafe4 100644 --- a/controllers/user.js +++ b/controllers/user.js @@ -377,9 +377,18 @@ exports.postUpdateProfile = function(req, res, next) { if (err) { return next(err); } - req.flash('success', {msg: 'Profile information updated.'}); - res.redirect('/account'); - resources.updateUserStoryPictures(user._id.toString(), user.profile.picture, user.profile.username); + resources.updateUserStoryPictures( + user._id.toString(), + user.profile.picture, + user.profile.username, + function(err) { + if (err) { return next(err); } + req.flash('success', { + msg: 'Profile information updated.' + }); + res.redirect('/account'); + } + ); }); }); });