簡體   English   中英

如何在中間突破承諾鏈

[英]How to break out of the promise chain in the middle

這是我的示例代碼。

Orchestrator首先用幾個輸入呼叫工作人員,獲得響應后,必須驗證響應是否令人滿意。

如果滿意,請返回給呼叫者。

如果不是,請再次致電相同的工作人員,也可以是其他工作人員,輸入稍有不同,然后按照流程進行操作。

在這里,盡管我的代碼在第一個工作程序調用之后調用cb(),但也將在第二個工作程序調用之后調用,並且未定義“響應”錯誤。

我可以添加一個額外的條件來檢查第一個響應是否令人滿意,例如第二個中的need2ndworkercall && validate(response)並擺脫它。 但是想知道什么是解決這個問題的正確方法。 感謝任何反饋。

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

從函數和.then() return值。 此外, 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)
  });

可以通過簡單的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
    }
  })

這是這種方法的最簡單演示: 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM