How to Use Axios with JavaScript Async/Await
Axios is a popular, Promise-based HTTP client for JavaScript,
designed to handle asynchronous web requests in both browser and Node.js
environments. Because modern JavaScript provides the
async/await syntax as a clean, synchronous-looking
abstraction over Promises, Axios integrates natively with it. This
article explains how Axios interacts with async/await,
demonstrating how to execute requests, process responses, manage errors,
and run concurrent operations efficiently.
The Core Interaction: Promises and Async/Await
Every request method in Axios—such as axios.get(),
axios.post(), or axios.delete()—returns a
standard JavaScript Promise.
The async/await syntax allows you to pause the execution
of an async function until that Promise settles (either
resolves or rejects). Instead of chaining .then()
callbacks, you place the await keyword directly in front of
the Axios call to extract the resolved response object directly.
import axios from 'axios';
async function fetchUserData(userId) {
const response = await axios.get(`https://api.example.com/users/${userId}`);
console.log(response.data);
}When using await, Axios resolves with an object
containing:
data: The payload returned by the server (automatically parsed from JSON).status: The HTTP status code (e.g., 200).statusText: The HTTP status message from the server.headers: The HTTP response headers.config: The original request configuration.
Handling Errors with
try...catch
In standard Promise chains, rejected promises are handled using
.catch(). When using async/await, Axios
rejects its Promise automatically whenever an HTTP request fails or
returns a status code outside the 2xx range.
These rejections are caught using traditional JavaScript
try...catch blocks.
async function createUser(userData) {
try {
const response = await axios.post('https://api.example.com/users', userData);
return response.data;
} catch (error) {
if (error.response) {
// The server responded with a status code outside the 2xx range
console.error('Server Error:', error.response.status, error.response.data);
} else if (error.request) {
// The request was made but no response was received (e.g., network down)
console.error('Network Error: No response received');
} else {
// An error occurred during request setup
console.error('Request Error:', error.message);
}
}
}Handling Concurrent Requests
When making multiple independent API requests, sequentially awaiting
each Axios call can introduce unnecessary latency. To run requests in
parallel while still using async/await, use
Promise.all() or Promise.allSettled().
async function getDashboardData() {
try {
const [userResponse, postsResponse] = await Promise.all([
axios.get('https://api.example.com/user/1'),
axios.get('https://api.example.com/user/1/posts')
]);
return {
user: userResponse.data,
posts: postsResponse.data
};
} catch (error) {
console.error('Failed to load dashboard data:', error);
}
}In this pattern, both HTTP calls are initiated simultaneously, and
execution pauses at await Promise.all until all requests
resolve or any single request fails.