在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ axios不用catch的寫法和使用catch的效果一樣嗎?

axios不用catch的寫法和使用catch的效果一樣嗎?

1.官網(wǎng)上的寫法是

axios.post(url, data)
    .then(response => {
        console.log(response);
    })
    .catch(error => {
           console.log(error);
    })

2.公司項目的寫法是

axios.post(url, data)
    .then(response => {
        console.log(response);
    }, error => {
        console.log(error);
    })

本人小白,之前沒怎么用過then和catch的寫法,請問這兩種寫法是一樣的效果嗎?謝謝了

回答
編輯回答
舊城人

推薦官網(wǎng)的寫法。

你們公司的寫法和官網(wǎng)的差別在于。 你公司的寫法無法catch第一個參數(shù)的異常。

也就是說

 console.log(response);

上面這塊代碼報錯,是無法捕獲的。

2018年5月13日 18:51
編輯回答
陌南塵

沒有什么誰好誰不好之說 主要看業(yè)務(wù)吧, 這樣寫可能容易看懂一些

axios.post(url, data)
    .then(response => {
        //處理邏輯
    }, error => {
        console.log('接口報錯');
    })
    .catch(error=>{
        console.log('處理邏輯出錯');
    })
axios.post(url, data)
    .then(response => {
        //處理邏輯
    })
    .catch(error=>{
        console.log('接口或處理邏輯出錯');
    })
2017年9月23日 00:22
編輯回答
未命名

首先 這個不是 axios catch 的相關(guān) 而是關(guān)于 new Promise() 的then
阮一峰在 promise 文檔寫的很清楚

一般來說,不要在then方法里面定義 Reject 狀態(tài)的回調(diào)函數(shù)(即then的第二個參數(shù)),總是使用catch方法。
// bad
promise
  .then(function(data) {
    // success
  }, function(err) {
    // error
  });

// good
promise
  .then(function(data) { //cb
    // success
  })
  .catch(function(err) {
    // error
  });
上面代碼中,第二種寫法要好于第一種寫法,理由是第二種寫法可以捕獲前面then方法執(zhí)行中的錯誤,也更接近同步的寫法(try/catch)。因此,建議總是使用catch方法,而不使用then方法的第二個參數(shù)。
2017年4月25日 20:02