Node.js Q promises then () chain does not wait
I am trying to refactor the following code to avoid the callback addon by converting it to:
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 can see, I created a method for each 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 the same console.log calls to be able to track the execution path.
I expect it to be:
- createUser
- createUser done
- createClient
- createClient done
- createClientPartner
- createClientPartner done
But instead this:
- CreateUser
- createClient
- createClientPartner
- createClientPartner done
- createUser done
- createClient done
Why do functions occur when the previous promise was not resolved? I expect that "then" wait until the previous promise is resolved or rejected to continue. Am I missing something important about promises?
+3
source to share
1 answer