Today, My mentor teach me how to create a weather-checking app using the OpenWeatherMap URL through an API. Then, we learned how fetch, async/await, and axios work in it.
API: Connecting two different domains.
Fetch():
fetch() is a built-in JavaScript function used to make HTTP requests (like GET, POST) from the browser to a server or an API.
fetch() is used to get or send data from/to APIs.
It returns a Promise
You need to manually convert the response using .json()
Example:
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);
})
async & await:
async and await are modern keywords used in JavaScript to handle promises more easily and clearly — instead of chaining .then().
They make asynchronous code look like synchronous code, which is easier to read and understand.
You put async before a function to make it return a Promise.
Inside this function, you can use await.
await can only be used inside an async function.
It waits for the promise to resolve before moving to the next line.
Example:
async function getData() {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
}
getData();
async Makes a function return a promise
await Pauses the async function until the promise resolves
Axois:
A promise-based HTTP client that's simpler and more powerful than fetch.
It works like fetch, but with more features and a simpler syntax.
Example:
import axios from 'axios';
axios.get('https://api.example.com/weather')
.then(response => console.log(response.data))
.catch(error => console.log("Error:", error));
Automatically parses JSON.
Axios is a powerful alternative to fetch.
It simplifies HTTP requests.