簡體   English   中英

async + axios 或只是 axios,這就是問題所在

[英]async + axios or just axios, that's the question

有區別嗎

useEffect(()=>{
  async function fetchData(){
    await axios
      .get(path, config)
      .then(resp=>console.log(resp))
      .catch(error=>console.log(error))
  }
  fetchData();
},[])

&

useEffect(()=>{
  axios
    .get(path, config)
    .then(resp=>console.log(resp))
    .catch(error=>console.log(error))
})

是否有一種更值得推薦或一種比另一種更貶值?

就結果而言,兩者都給出相同的結果,“異步”更新,但除此之外還有什么?

謝謝,

async通常與 await 結合使用。 通常,如果您不打算在 function 中聲明 await,則無需使用 async。 但是, async使編寫異步代碼更簡潔。 在第一個例子中

useEffect(()=>{
  async function fetchData(){
    await axios
      .get(path, config)
      .then(resp=>console.log(resp))
      .catch(error=>console.log(error))
  }
  fetchData();
},[])

.then.catch子句是多余的,因為您可以輕松地以更簡潔的方式重寫它:

    useEffect(()=>{
      async function fetchData(){
       try{
        const result = await axios.get(path, config)
        console.log(result)
       }catch(e){
          console.log(e)
       }
      }
      fetchData();
    },[])

這最大限度地減少了進入“回調地獄”的機會,因為異步函數可以以同步方式編寫,這取決於您的偏好,更直觀,並允許您直接從聲明的 function 返回結果。

但是,當您不需要聲明的 function 的結果時, .then.catch子句確實會派上用場,並且有時可以更快地編寫。 對於大多數開發人員來說,這取決於個人喜好,盡管如果您在雲基礎設施中開發並使用AWS Lambda功能,那么考慮到雲開發的事件驅動和功能性質, async/await變得更加重要,您無法真正堅持下去state 很容易。

你實際上混合了不同的語法。

第一個是獲取請求的 async/await 方法,它更像這樣:

try{
const response = await axios.get(request)
return response
}
catch(err){
return err
}

第二個使用 then 和 catch 是這樣的:

const response = axios.get(request).then(res=>return res).catch(err=>return err);

現在這兩種方式都是做同樣的事情的不同方式,但是,async/await 是更新的和更簡潔的語法,可以提高代碼的可讀性。 所以通常更傾向於使用 async/await 語法

我希望我的答案與@ArkyAsmals 的答案混合在一起對您有所幫助!

暫無
暫無

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

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