有很多方法可以解決這個問題,但基本上你必須改變鏈條結構或功能本身。
在這種情況下,我會敷getLighterfluid
有這樣的幫手:
function conditionally(predicate, handler) {
return function(val) {
if(predicate(val) {
return handler(val);
}
};
}
function notEqualFunc(val) {
return function(v) {
return v != val;
};
}
getMoney()
.then(getBeer)
.then(getFireworks)
.then(conditionally(notEqualFunc('No fireworks available'), getLighterfluid))
.then(getCrazy);
,你可以:
getMoney()
.then(getBeer)
.then(getFireworks)
.then(function(val) { if(val != 'No fireworks available') return getLighterfluid(val); })
.then(getCrazy);
如果你需要經常使用它你可以概括這種模式創建您需要的任何謂詞原型而不是notEqualFunc
,並使代碼具有相當的描述性。
'getLighterFluid'只能檢查是否有煙花。如果沒有,什麼都不要做。 – Oskar
'.catch(getAmbulance)' – Bergi