I'm using promises to call a serie of webservices, but I'd like, in some cases, use redirection in the middle of my logic. The problem is that the promises chain continue to execute after the redirection occured.
Here is the code:
myfunc = function() {
return PromiseCall1()
.then(function(data){
if (condition){
$location.path(some_url); // This is a redirection with AngularJS
} else {
return PromiseCall2();
}
})
.then(function(data){
return PromiseCall3();
})
.then(function(data){
// Some other stuff here
})
};
The expected behaviour would be:
PromiseCall1()
must be called
- if
condition
is true, no other promise must be called, just do the redirection
- if
condition
is false, Promise2 then Promise3 must be called.
How would you do it?
Thank you for your help.
func = function () {
return PromiseCall1().then(function (data) {
if (condition) {
$location.path(some_url); // This is a redirection with AngularJS
} else {
return PromiseCall2().then(function (data) {
return PromiseCall3();
}).then(function (data) {
// Some other stuff here
});
}
});
};
Petka's solution is ok. If you want. It is possible if you wrap your then handlers with Maybe.
Something like:
var maybe = function(fn){
return function(value){
if(value === maybe.Nothing) return maybe.Nothing;
return fn.apply(this,arguments);
};
});
maybe.Nothing = {}; // unique reference
Which would let you do
Promise.try(function(){
return 15;
}).then(maybe(function(val){
console.log("got",val);
return maybe.Nothing;
})).then(maybe(function(val){
console.log("This never gets called");
}));
This gives you an explicit value hook to signal not continuing any promise in the chain that is wrapped with a maybe.