[英]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.