2017-04-17 60 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