RadleyMith
RadleyMith

Reputation: 1343

Promises .then() with one argument

I am having trouble interpreting what the Promises/A+ spec meant by this...

https://promisesaplus.com/#point-23

If you have a promise and call .then with one argument, does that mean that the single argument will be called regardless of success or failure?

I feel like it could go either way with interpreting this. I guess the library I would be most concerned with is Q.

Upvotes: 3

Views: 1244

Answers (3)

jfriend00
jfriend00

Reputation: 707228

The first argument to a .then() handler, whether it is the only argument or not, is always the fulfilled handler and is only called if the promise is fulfilled. That first argument is not treated differently if there is or is not a second argument passed.

Upvotes: 4

RadleyMith
RadleyMith

Reputation: 1343

So to anyone who is unsure, I made a test script that you can run in your node REPL. The definitive answer is that no it will not call the success with an err attachment.

var Q = require('q');

//call with whether or not the promise will resolve
function aPromise (bool) {
    var def = Q.defer();
    if (!bool) {
        def.reject("oooo0o0o00o0 rejected");
    }
    def.resolve('winner winner chicken dinner');
    return def.promise
}

var whatGonnaBe = aPromise(false)

//The Example
whatGonnaBe
.then(function (response) {
    console.log('1')
    console.log(JSON.stringify(response) + '1');
})
.then(function (response) {
    console.log('2')
    console.log(JSON.stringify(response) + '2');
},
function (response) {
    console.log('3')
    console.log(JSON.stringify(response) + '3');
})

Upvotes: 2

Ryan Wheale
Ryan Wheale

Reputation: 28390

No, the first argument is always the "success" or "resolved" argument. The second argument is always the failure argument, and you can omit it when chaining promises together and have a single "fail" argument to handle all fails. This code is just conceptual:

promise1.then(function() {
    return promise2;
}).then(function() {
    return promise3;
}).then(function() {
    /* everything succeeded, move forward */
}, function() {
    /* catch any failure by any of the promises */
});

Upvotes: 1

Related Questions