Today, I learned some very useful things in JavaScript that help to handle asynchronous tasks. These topics were Promise, async/await, fetch, and axios.
What is a Promise?
A Promise is used in JavaScript to handle tasks that take some time, like getting data from a server. It has three states:
Pending – waiting for the result
Resolved – task completed successfully
Rejected – task failed
Example:
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Data received!");
} else {
reject("Something went wrong!");
}
});
What is async/await?
async and await make it easier to work with Promises. Instead of .then() and .catch(), we can write code like normal steps.
Example:
async function getData() {
let result = await fetch("https://api.example.com/data");
let data = await result.json();
console.log(data);
}
getData();
What is fetch?
fetch() is used to get data from a web API. It returns a Promise.
Example:
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
What is Axios?
Axios is another way to fetch data from APIs. It is easier and has more features than fetch.
Example:
axios.get("https://api.example.com/data")
.then(response => console.log(response.data))
.catch(error => console.log(error));