【Js】不使用try catch,優雅地處理await報錯的狀況

const res = await jiekou(params);
if(res.code === 0) {
//執行代碼
} else {
// 錯誤處理
}

相似場景景:若是jiekou報500,那不會走到下面的if判斷,那相應的代碼都不會執行。javascript


解決方式:java

// 寫一個方法去執行本來的操做,若是有錯誤返回[err],沒有錯誤返回[null, res]
function getAwaitResult(promise) {
   return promise.then(res => {
      return [null, res];
   })
   .catch(err => [err]);
}

使用promise

const [err, res] = await getAwaitResult(jiekou(params));
if (err) {
  // 例如此處須要不顯示loading
  this.loading = false;
  this.$message.error(String(err));
  return;
}
// 後面執行res的正常操做就好
if (res.code === 0) {
  this.imageList = res.data.list;
  this.total = res.data.total;
} else {
  this.$message.error(res.msg);
}

參考:https://blog.grossman.io/how-...async

相關文章
相關標籤/搜索