DEV Community

P Mukila
P Mukila

Posted on

Today i Learned - fetch, async & await, axios...

fetch
The fetch() API in JavaScript provides a modern and flexible interface for making network requests, primarily designed to replace the older XMLHttpRequest. It allows you to fetch resources like JSON data, HTML, images, and more from a server.

Basic Syntax

fetch(url, options) .then(response => response.json()) .then(data => { // Do something with the data }) .catch(error => { // Handle any errors }); 
Enter fullscreen mode Exit fullscreen mode

Parameters

  • url: The URL to which the request is sent.

  • options (optional): An object that allows you to configure the request (method, headers, body, etc.).

Key Points

  • fetch returns a Promise.

  • It won’t reject on HTTP errors like 404 or 500 — you have to check response.ok.

Example:

function getWeather() { const apiKey = "2a50fd8aa879e6af857307fdc1a16bc6"; const url = `http://api.openweathermap.org/data/2.5/ weather?q=${city}&appid=${apiKey}&units=metric`; fetch(url) .then((res) => { return res.json(); }).then((data) => { console.log(data.main.feels_like); result.innerHTML = `Temperature : ${data.main.temp}` }).catch((error) => { console.log(error); 
Enter fullscreen mode Exit fullscreen mode

async:

A function declared with async always returns a Promise.

async function getData() { return "Hello"; } 
Enter fullscreen mode Exit fullscreen mode

Calling getData() returns a Promise that resolves to "Hello".
await:
You use await inside async functions to pause the code until a Promise is resolved.

async function fetchData() { let response = await fetch('https://api.example.com/data'); let data = await response.json(); console.log(data); } 
Enter fullscreen mode Exit fullscreen mode

Axios:

Axios is a promise-based HTTP client for browsers and Node.js. It simplifies making requests to APIs and handling responses.

Installing Axios:

Use npm or yarn:

npm install axios 
Enter fullscreen mode Exit fullscreen mode

Or use a CDN in your HTML:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Or with async/await:

async function fetchPosts() { try { const res = await axios.get('https://api.example.com/posts'); console.log(res.data); } catch (err) { console.error('Axios error:', err); } } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)