//Synchronous example
console.log("Start");
console.log("Middle");
console.log("End");
//Asynchronous example
console.log("Start");
setTimeout(() => {
console.log("Async Task");
}, 2000);
console.log("End");
function fetchData(callback) {
//Simulating an asynchronous task using setTimeout
setTimeout(() => {
//Calling the callback function after 2 seconds
callback("Data received");
}, 2000);
}
//Passing a function as a callback
fetchData((message) => {
console.log(message);
});
In this example, the callback ensures that the code inside it runs only after the asynchronous task is completed.
Callbacks were widely used before Promises. However, using many nested callbacks can make code difficult to read and maintain. This situation is known as callback hell, which is why modern JavaScript prefers Promises and async/await.
const getData = new Promise((resolve, reject) => {
//Simulating success or failure
let success = true;
if (success) {
//Promise completed successfully
resolve("Data loaded successfully");
} else {
//Promise failed
reject("Error loading data");
}
});
Promises provide a structured way to handle asynchronous operations, which is why modern JavaScript and React applications rely on them.
getData
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
async function loadData() {
const message = await getData;
console.log(message);
}
loadData();
async function loadData() {
try {
const result = await getData;
console.log(result);
} catch (error) {
console.log("Error:", error);
}
}
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});
| Method | Purpose |
|---|---|
| GET | Fetch data |
| POST | Create new data |
| PUT | Update existing data |
| DELETE | Remove data |
async function getUsers() {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const users = await response.json();
console.log(users);
}
let isLoading = true;
let error = null;
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(data => {
isLoading = false;
console.log(data);
})
.catch(err => {
isLoading = false;
error = err;
console.log("Error occurred");
});