Coding Triumph

Helpful code snippets & tutorials

How to use async/await with axios.js in JavaScript

Axios.js is a JavaScript library for making HTTP requests based on promises. We usually use the then-catch syntax when working with axios.js, but if you prefer the async/await syntax, I’ll show you how to do that.

The then-catch syntax:

// a simple GET request
axios.get('/my-url')
  .then( (response) => {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

The async/await syntax:

// execute axios inside an async function
async function getRequest() {
  try {
    const response = await axios.get('/my-url');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}
// call the async function
getRequest();
If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments