Reputation: 2835
Why does 'good' and 'Error is called' write the console in the below example?
My understanding is that you give then() something to run on success and something to run on fail?
var deferred = Q.defer();
function two() {
deferred.resolve();
return deferred.promise;
}
two().then(console.log('good'),console.log('Error is called'));
Upvotes: 2
Views: 2228
Reputation: 239683
Q.then
function can actually accept three parameters and all of them should be functions.
The success handler
The failure handler
The progress handler
When you do,
two().then(console.log('good'), console.log('Error is called'));
you are actually passing the result of executing both the console.log
s to the then
function. The console.log
function returns undefined
. So, effectively, you are doing this
var first = console.log('good'); // good
var second = console.log('Error is called'); // Error is called
console.log(first, second); // undefined, undefined
two().then(first, second); // Passing undefineds
So, you must be passing two functions to the then
function. Like this
two().then(function() {
// Success handler
console.log('good');
}, function() {
// Failure handler
console.log('Error is called')
});
But, Q
actually provides a convenient way to handle all the errors occur in the promises at a single point. This lets the developer not to worry much about error handling in the business logic part. That can be done with Q.fail
function, like this
two()
.then(function() {
// Success handler
console.log('good');
})
.fail(function() {
// Failure handler
console.log('Error is called')
});
Upvotes: 3
Reputation: 56587
You have to pass functions to .then
. What you did is you called console.log('good')
and passed the result of calling it (which is undefined)
to .then
. Use it like that:
two().then(
function() { console.log('good'); },
function() { console.log('Error is called'); }
);
Upvotes: 3