Home > OS >  async axios or just axios, that's the question
async axios or just axios, that's the question

Time:09-16

is there a difference between

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))
},[])

is there one that is more recommended or one that is more depreciated than the other one?

in terms of results both give the same, the "async" is newer, but other than that is there something?

thanks,

CodePudding user response:

async is typically used with conjunction with await. Usually, if you aren't going to declare await in the function, there's no need to use async. However, async makes writing asynchronous code cleaner. In the first example

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

the .then and .catch clauses are redundant since, you can easily re-write this in a cleaner fashion:

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

This minimizes the chance of entering "callback hell" because asynchronous functions can be written in a synchronous way, which depending on your preference, is more intuitive and allows you to return a result directly from a declared function.

However, .then and .catch clauses do come in handy when you don't need a result from the declared function, and can sometimes be faster to write. For most developers it comes down to personal preference, although if you develop in cloud infrastructure, and use AWS Lambda functions, async/await becomes more essential given the event-driven, and functional nature of cloud development, where you can't really persist state easily.

CodePudding user response:

you're actually mixing up to different syntaxes.

The first one is the async/await method of getting requests which is more like this:

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

The second one using then and catch is like this:

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

Now both of these are different ways of doing the same exact thing, however, async/await is newer and a cleaner syntax which improves code readability. So it is usually more preferred to use the async/await syntax

I hope my answer mixed with @ArkyAsmals answer helps you !

  • Related