2015-11-12 21 views
2

我有4個異步功能在我的節點應用程序中以瀑布風格執行。nodeJS設計模式打破async.waterfall或promise.then然後

async.waterfall將整理它,但基於第一個函數的結果,我要麼錯誤,進行下來的瀑布或爆發到完成的功能。

現在沒有辦法做到這一點(除了錯誤,成功的價值,這只是聞起來不好)。 (藍鳥),但我再看不到一種方法,如果我不在.then中返回另一個承諾,那麼將執行下面的所有.then s,但是,具有空參數。

是否有其他模式/實用程序可以提供幫助?

還是我在想這個,只是先調用第一個方法,然後根據結果運行async.waterfall,或者返回結果!

假設我有4種功能調用,A,B,C,d .....

async.waterfall([ 
    function(cb) { 
     a("some data", cb) 
    }, 
    function(data, cb) { 
     if(data) { 
      // HERE we want to skip the remaining waterfall a go to the final func 
     } else { 
      b("some data", cb); 
     } 
    }, 
    c, 
    d 
], 

function(err, data) { 
    //do something 
}); 

或者,如果他們的承諾...

a("some data") 
.then(function(data) { 
    if(data) { 
     // here I want to stop executing the rest of the promises... 
    } else { 
     return b("some data") 
    } 
}) 
.then(c) 
.then(d) 
.catch(function(err) { 
    //log error 
}) 
.finally(function() { 
    // do something 
}) 

我想我應該這樣做......

function doit(data, done) { 
    a("some data", function(err, data) { 
     if(err) { return done(err) }; 
     if(data) { return done(null, data) }; 

     //Here we run the waterfall if the above doesn't exist. 

     async.waterfall([ 
      function(cb) { 
       b("some data", cb) 
      }, 
      c, 
      d 
     ], 
     function(err, data) { 
      done(err, data); 
     }); 
} 
+0

我認爲用一些特定的參數調用'cb'有這種效果。但我認爲這會將代碼導向錯誤分支。 –

+0

是的,你可以做'cb(「success」,data)',然後在最終的函數中檢查err ==「success」,但它不是一個很乾淨的解決方案... –

回答

1

有了承諾,你可以附上「後續承諾」的執行分支,你需要:

a("some data") 
.then(function(data) { 
    if(data) { 
     return "foo";//other promises won't be executed here 
    } else { 
     return b("some data").then(c).then(d) 
    } 
}) 
.catch(function(err) { 
    //log error 
}) 
.finally(function() { 
    // do something 
}) 
+0

啊哈!無法看到樹木的木材!謝謝。 –

+0

@MattBryson不客氣。或者,你可以鏈接承諾,如你的問題和處理程序檢查是否有任何參數傳遞給它,如果沒有,只需調用'return' –