Reputation: 1124
I am trying to refactor the following code to avoid the callback hell, transforming it into:
createUser(user_data)
.then(createClient(client_data))
.then(createClientPartner(clientpartner_data))
.then(function(data) {
cb(null, _.pick(data,['id','username']));
}, function(error) {
cb(error);
});
As you see, I created a method for each one of the steps:
function createUser(user_data) {
console.log('createUser');
var deferred = Q.defer()
new db.models.User.create(user_data, function(err, user) {
console.log('createUser done');
if (!!err)
deferred.reject(err);
else {
client_data['id'] = user.id;
deferred.resolve(user);
}
});
return deferred.promise;
}
The other methods have identical console.log calls to be able to follow the execution path.
I would expect it to be:
But instead, it is:
Why does are the functions triggered when the previous promise have not been resolved? I expect "then" to wait until previous promise have been resolved or rejected to continue. Am I missing something important about promises?
Upvotes: 4
Views: 1139
Reputation: 382150
The problem is you don't pass functions, but the result of function calls.
Instead of
createUser(user_data)
.then(createClient(client_data))
you should have
createUser(user_data)
.then(function(user){
createClient(client_data) // no need for the user ? really ?
})
Upvotes: 5