Domanda

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'));
È stato utile?

Soluzione

Q.then function can actually accept three parameters and all of them should be functions.

  1. The success handler

  2. The failure handler

  3. 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.logs 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')
    });

Altri suggerimenti

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'); }
);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top