[英]Using redirections into promises chain
我正在使用 Promise 来调用一系列网络服务,但在某些情况下,我希望在我的逻辑中间使用重定向。 问题是在重定向发生后,promise 链会继续执行。
这是代码:
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
})
};
预期的行为是:
PromiseCall1()
必须被调用condition
为真,则不必调用其他承诺,只需进行重定向condition
为假,则必须调用 Promise2 然后 Promise3。你会怎么做? 感谢您的帮助。
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的解决方案是可以的。 如果你想。 如果你用 Maybe 包装你的 then 处理程序,这是可能的。
就像是:
var maybe = function(fn){
return function(value){
if(value === maybe.Nothing) return maybe.Nothing;
return fn.apply(this,arguments);
};
});
maybe.Nothing = {}; // unique reference
哪个会让你做
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");
}));
这为您提供了一个显式的值挂钩,以表示不会继续在用 may 包裹的链中的任何承诺。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.