DEV Community

Tamilselvan K
Tamilselvan K

Posted on

Day-47 Today I learned Fetch, Async/Await & Axios in JavaScript

What is Fetch?

Fetch is a built-in JavaScript function used to make HTTP requests. It returns a Promise and is commonly used to interact with APIs. It requires manual response parsing using .json() and handles asynchronous operations with either .then() chaining or async/await.

Example with Fetch using .then()

function getWeather() {
    const city = document.getElementById('input-value').value;
    const result = document.getElementById('result');
    const apiKey = "YOUR_API_KEY_HERE";
    const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;

    fetch(url)
        .then((response) => {
            return response.json();
        })
        .then((data) => {
            console.log(data);
            result.innerHTML = `Temperature: ${data.main.temp} 
                                 Humidity: ${data.main.humidity}`;
        })
        .catch((error) => {
            console.log(error);
            result.innerHTML = "City not found";
        });
}
Enter fullscreen mode Exit fullscreen mode

How It Works

  1. The function reads the city name from the input field.
  2. Forms the URL with the API key and city.
  3. Uses fetch to request weather data.
  4. Parses the JSON response.
  5. Displays temperature and humidity or error if any.

What is Async and Await?

Async and Await are used to write asynchronous code in a way that looks synchronous, making it cleaner and easier to read. The async keyword is used before a function, and await is used before any Promise that needs to resolve.

Example with Fetch using Async/Await

async function getWeather() {
    const city = document.getElementById('input-value').value;
    const result = document.getElementById('result');
    const apiKey = "YOUR_API_KEY_HERE";
    const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;

    try {
        const response = await fetch(url);
        const data = await response.json();
        result.innerHTML = `Temperature: ${data.main.temp}
                             Humidity: ${data.main.humidity}`;
    } catch (error) {
        console.log(error);
        result.innerHTML = "City not found";
    }
}
Enter fullscreen mode Exit fullscreen mode

How It Works

  1. Declares the function with async.
  2. Uses await to wait for the fetch request.
  3. Parses the response with await response.json().
  4. Displays the result or error message.

What is Axios?

Axios is a third-party JavaScript library used to make HTTP requests. It simplifies fetch operations by handling JSON parsing automatically and providing better error handling.

Example with Axios using Async/Await

async function getWeather() {
    const city = document.getElementById('input-value').value;
    const result = document.getElementById('result');
    const apiKey = "YOUR_API_KEY_HERE";
    const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;

    try {
        const response = await axios.get(url);
        result.innerHTML = `Temperature: ${response.data.main.temp}°C <br> 
                             Humidity: ${response.data.main.humidity}%`;
    } catch (error) {
        console.log(error);
        result.innerHTML = "City not found";
    }
}
Enter fullscreen mode Exit fullscreen mode

How It Works

  1. Uses the axios.get() method to fetch data.
  2. Axios automatically parses the JSON response.
  3. Handles errors cleanly with try...catch.
  4. Displays temperature and humidity from response.data.

Conclusion

  • Fetch with .then() works but can look messy with chaining.
  • Fetch with async/await simplifies the code and improves readability.
  • Axios further simplifies the process by handling JSON parsing automatically and offering better error handling.

Top comments (4)

Collapse
 
dotallio profile image
Dotallio

Nice breakdown! For real projects, do you prefer Axios over Fetch, or stick with native Fetch plus helpers?

Collapse
 
tamilselvan1812 profile image
Tamilselvan K

I usually prefer native fetch with helpers to keep things lightweight. But if the project needs features like request cancellation, timeouts, or better error handling, Axios is a solid choice

Collapse
 
emboe profile image
Emily

That's awesome. I want to start learning about it too.

Collapse
 
tamilselvan1812 profile image
Tamilselvan K

Nicee! You’re gonna enjoy it for sure