Use Axios with Async/Await

发布于2022-12-23, 文章约161字, 阅读约需1分钟。


What is Axios?

Axios is a promise-based HTTP client that lets you handle asynchronous HTTP requests.

It uses JavaScript’s promises to send HTTP requests and manage their responses.

Installation

Let’s install Axios in our project by running the following command in the project terminal:

npm install axios

Axios with async/await

A better and cleaner way of handling promises is through the async/await keywords.

You start by specifying the caller function as async. Then use the await keyword with the function call.

Due to the await keyword, the asynchronous function pauses until the promise is resolved.

import axios from 'axios';

const getData = async () => {
    const response = await axios.get(
        `https://example.com/api/random`
    );
};

Error handling with Async/Await

To handle errors in a standard API call using Axios with Async/Await, we use a try…catch block.

Inside the catch, we can handle errors. Here is an example:

try {
    const res = await axios.get(`https://example.com/api/random`);
} catch (error) {
    // Handle errors
}