I am currently running an API in Node.JS with the Sails.js framework. I am using promises for the first time, and I have some problems to synchronize my promises as I want.
My main function is as follows:
createCard: function(req, res) {
checkIfUserHasStripeAccount(req.user)
.then(addCreditCardToStripeAccount())
.then(function cardCreated() {
res.send(200, {
msg: 'Card created'
});
})
.catch(function handleError(err) {
res.send(err.httpCode, err.msg);
})
},
Obviously, I cannot add a credit card to my stripe account if the user does not have one.
The checkIfUserHasStripeAccount () function checks if an account exists, and if not, create one.
Here is the code for this part:
function checkIfUserHasStripeAccount(user) {
var deferred = q.defer();
if (!user.idStripe) {
createStripeAccountToUser(user)
.then(function(savedUser) {
deferred.resolve(savedUser);
})
.catch(function(err) {
deferred.reject(err);
})
} else {
deferred.resolve(user);
}
return deferred.promise;
}
function createStripeAccountToUser(user) {
var deferred = q.defer();
var jsonUserToCreate = {
description: user.firstname + ' ' + user.surname,
email: user.email
};
stripe.customers.create(jsonUserToCreate, function(err, customer) {
if (err) {
deferred.reject({
httpCode: 500,
msg: 'some error'
});
} else {
user.idStripe = customer.id;
user.save(function(err, savedUser) {
if (err) {
deferred.reject({
httpCode: 500,
msg: 'some error'
});
}
deferred.resolve(savedUser);
});
}
});
return deferred.promise;
}
The problem is what .then(addCreditCardToStripeAccount())
is done before completion checkIfUserHasStripeAccount()
.
I can’t understand why. I thought it .then(addCreditCardToStripeAccount())
would only be executed if he received a rejection or permission.