簡體   English   中英

如何通過錯誤處理順序運行 Promise

[英]How to sequentially run promises with error handling

我需要依次調用 3 個請求,它們都有 3 個分辨率

  • 如果請求為 200 且響應正常,則調用另一個請求
  • 如果請求是 200,但響應不好,做點什么
  • 如果請求不成功,請執行其他操作

快樂的道路看起來像這樣:

const firstCallResponse = await this.service1.call1();
if (firstCallResponse) {
  const secondCallResponse = await this.service2.call2();
  if (secondCallResponse) {
    const thirdCallResponse = await this.service3.call3();
    if (thirdCallResponse) {
      console.log('sequence finished successfully);
    }
  }
}

它看起來並沒有那么糟糕,但是如果我嘗試為每個請求添加這兩個后備,代碼會變得非常混亂。

try {
  const firstCallResponse = await this.service1.call1();
  if (firstCallResponse) {
    try {
      const secondCallResponse = await this.service2.call2();
      if (secondCallResponse) {
        try {
          const thirdCallResponse = await this.service3.call3();
          if (thirdCallResponse) {
            console.log('sequence finished successfully');
          } else {
            console.log('do something, as third call response is not ok');
          }
        } catch {
          console.log('do something as third call failed');
        }
      } else {
        console.log('do something, as second call response is not ok');
      }
    } catch {
      console.log('do something as second call failed');
    }
  } else {
    console.log('do something, as first call response is not ok');
  }
} catch {
  console.log('do something as first call failed');
}

有沒有辦法讓這段代碼更具可讀性或更優雅? 上面的代碼可以工作,但它看起來不太好,而且非常難以閱讀。 提前致謝!

首先,如果你想在它們失敗時做同樣的事情,你可以用try / catch包裝多個 promise。 還接受 catch 塊中的參數,因為它們可以告訴您錯誤的來源/有關它的更多信息 aka

try {
  // await promise
} catch (errorName) {
  // handle error
}

除了我建議的主要事情是通過檢查結果接下來要做什么並添加return語句來反轉你的邏輯。

try {
  const firstCallResponse = await this.service1.call1();
  if (!firstCallResponse) {
    console.log('do something as first call failed');
    return;
  }

  const secondCallResponse = await this.service2.call2();
  if (!secondCallResponse) {
    console.log('do something as second call failed');
    return;
  }

  // ...
  // if no errors do something with all results
} catch {
  console.log('do something as first call failed');
}

我想為結束添加的另一個提示是,如果您的第二次通話不需要第一次通話的結果中的任何內容,您可以將它們全部分組到一個承諾中

await Promise.all([
  this.service1.call1(),
  this.service2.call2()
])

暫無
暫無

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

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