Reputation: 1330
take a look at the example code below, I wonder if it is enough to just chain one .catch()
on the outer most sequelize task instead of always chaining it on each task which looks quite messy.
The second question would be is it possible to make .then(instance, error)
contain the error object if there is any? like in mongoose the 1st argument is always the err obj. So i don't have to .catch
an error but simply handle it in the .then()
callback fn.
function facebookStrategy() {
return new FacebookStrategy({
clientID: config.facebook.app_id,
clientSecret: config.facebook.app_secret
}, function (accessToken, refreshToken, profile, done) {
process.nextTick(function () {
models.User.findOrCreate({
where: {email: profile.emails[0].value}
}).spread(function (user, created) {
models.UserPassport.findOrCreate({
where: {
// TODO(tsm): check out sequelize composite keys
method: 'facebook',
social_id: profile.id
},
defaults: {
method: 'facebook',
token: accessToken,
social_id: profile.id
}
}).spread(function (userPassport, created) {
userPassport.setUser(user).then(function () {
user.updateAttributes({
first_name: profile.name.givenName,
last_name: profile.name.familyName
}).then(function () {
return done(null, user);
});
});
}).catch(function (err) {
console.log('Error occured: ', err);
return done(err);
});
}).catch(function (err) {
console.log('Error occured: ', err);
return done(err);
});
})
})
}
Upvotes: 2
Views: 6914
Reputation: 32127
By returning a promise you can chain it.
So you can do something like
function facebookStrategy() {
return new FacebookStrategy({
clientID: config.facebook.app_id,
clientSecret: config.facebook.app_secret
}, function (accessToken, refreshToken, profile, done) {
process.nextTick(function () {
models.User.findOrCreate({
where: {
email: profile.emails[0].value
}
}).spread(function (user, created) {
return models.UserPassport.findOrCreate({
where: {
// TODO(tsm): check out sequelize composite keys
method: 'facebook',
social_id: profile.id
},
defaults: {
method: 'facebook',
token: accessToken,
social_id: profile.id
}
}).spread(function (userPassport, created) {
return userPassport.setUser(user).then(function () {
return user.updateAttributes({
first_name: profile.name.givenName,
last_name: profile.name.familyName
}).then(function () {
return done(null, user);
});
});
});
}).catch(done);
});
});
}
Upvotes: 2