Q and promises chaining

90 views Asked by At

Let say A() returns a resolved promise and go to B(). However, in some conditions, i need B() to finish and not execute the next then() ( I don't want to go in C(). I could use defered.reject() within B() method but it does not seem right.

var p = pull(target)
.then(function (data) {
    return A();
})
.then(function (data) {
    return B();
})
.then(function (data) {
    return C();
})

Any hint ?

2

There are 2 answers

0
Benjamin Gruenbaum On BEST ANSWER

Your way to do branching with promises is the same as it is without them - by an if condition mostly:

var p = pull(target)
.then(A).then(B)
.then(function (data) {
    if(data) return C(); // assuming B's resolution value is a boolean
});
1
Artūras On

How about just wrapping it inside same then method?

 var p = pull(target)
            .then(function(data) {
                return A();
            })
            .then(function(data) {
                var result = B();
                if (!result)
                    return C()
                return result;
            })