2017-04-17 95 views
0

這是我的示例代碼。如何擺脫中間的承諾鏈

協調員首先調用了幾個輸入的工作人員,一旦得到響應,就必須驗證響應是否令人滿意。

如果滿意,只需返回給調用者。

如果不是,再次調用同一個工人或者可能是不同的工人,輸入略有不同,並按照流程。

在這裏,雖然,我的代碼調用CB()的第一個工人電話後,它也將第二則和錯誤進行「響應」未定義等。

我可以添加額外的條件檢查第一個響應是否令人滿意,就像need2ndworkercall & &然後在第二個驗證(響應)然後擺脫它。但想知道處理這個問題的正確方法是什麼。欣賞任何反饋。

function orchestrateSomething(input, cb){ 
    doSomething(input.a, input.b) 
     .then(response=>{ 
     if(validate(response)){ 
      cb(buildResultObj(response)); 
     } 
     else{ 
      return doSomething(input.a) 
     } 
     }) 
     .then(response=>{ 
     if(validate(response)){ 
      cb(buildResultObj(response)); 
     } 
     else{ 
      cb(null,{}); 
     } 
     }) 
     .catch(error=>cb(error)); 
    } 
+0

你的Wi如果你想有條件地執行鏈的某個部分,你會想創建分支而不是直鏈。搜索「承諾分支與鏈」,你會發現許多文章(一些在stackoverflow)解釋。 – jfriend00

+0

請參閱[multiple,sequential fetch()Promise](http://stackoverflow.com/questions/38034574/multiple-sequential-fetch-promise/) – guest271314

回答

0

return value from function and .then()。此外cb函數應該調用傳遞函數返回值或評估參數和返回值傳遞

function orchestrateSomething(input, cb){ 
    return doSomething(input.a, input.b) 
     .then(response=>{ 
     if(validate(response)){ 
      return cb(buildResultObj(response)); 
     } 
     else{ 
      return doSomething(input.a) 
     } 
     }) 
     .then(response=>{ 
     if(validate(response)){ 
      return cb(buildResultObj(response)); 
     } 
     else{ 
      return cb(null,{}); 
     } 
     }) 
     .catch(error=>cb(error)); 
    } 

    orchestrateSomething(input, cb) // where `cb` calls function or values passed 
    .then(function(results) { 
    console.log(results) 
    }) 
    .catch(function(err) { 
    console.log(err) 
    }); 
0

有可能通過簡單的throw打破諾言鏈。關鍵是要妥善處理好它的catch電話:

doPromise(...) 
    .then(...) 
    .then(result => { 
    if(condition) { 
     throw result 
    } 
    else { 
     return doPromise() 
    } 
    }) 
    .then(...) 
    .catch(result => { 
    if(result instanceof Error) { 
     // handle error result 
    } 
    else { 
     // handle desired result 
    } 
    }) 

這裏有這樣的方法的simpliest演示:http://plnkr.co/edit/H7K5UsZIueUY5LdTZH2S?p=preview

順便說一句,如果你能概括then處理功能,可以使一個遞歸調用:

processCB = (result) => { 
    if(condition) { 
    throw result 
    } 
    else { 
    return doPromise() 
    } 
} 

catchCB = (result) => { 
    if(result instanceof Error) { 
    // handle error result 
    } 
    else { 
    // handle desired result 
    } 
} 

doProcess =() => doPromise() 
    .then(processCB) 
    .catch(catchCB) 

而這裏的第二塊演示:http://plnkr.co/edit/DF28KgBOHnjopPaQtjPl?p=preview