2017-04-17 1 views
0

ここに私のサンプルコードがあります。中期の約束を解消する方法

Orchestratorは、最初に2つの入力を使用してワーカーを呼び出し、応答を取得すると、応答が満足できるかどうかを検証する必要があります。

満足できる場合は、発信者に戻ってください。

もう一度、同じ従業員を呼び出すか、若干異なる入力をして別の従業員になり、その流れに従います。ここで

、私のコードは、CB(呼び出しが)最初のワーカーコールの後、それがまた出て2番目に行くとエラーの「応答」など、未定義..です

私がチェックするために、余分な条件を追加することができます1回目の応答が満足できるかどうか、need2ndworkercall & & 2回目に検証(応答)して取り除く。しかし、この問題に対処する正しい方法は何か不思議です。フィードバックを感謝します。

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:

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) 

そして、ここでは、二枚のデモですチェーンの一部を条件付きで実行したい場合は、直鎖ではなく、分岐を作成します。 "promise branch vs. chain"を検索すると、説明している記事(stackoverflow上の記事)が多数見つかります。 – jfriend00

+0

[複数、シーケンシャルfetch()Promise](http://stackoverflow.com/questions/38034574/multiple-sequential-fetch-promise/)を参照してください。 – guest271314

答えて

0

return value from functionおよび.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経由約束チェーンを破ることができます。

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 
    } 
    }) 

ここでは、そのようなアプローチの最も単純デモです:あなたはthen処理機能を一般化することができた場合、それをすることが可能となり、ところでhttp://plnkr.co/edit/H7K5UsZIueUY5LdTZH2S?p=preview

トリックはcatchコールにそれを適切に処理することです再帰呼び出し:http://plnkr.co/edit/DF28KgBOHnjopPaQtjPl?p=preview

関連する問題