How To Return the Response From an Asynchronous Call in JavaScript?
Last Updated :
28 Oct, 2024
To return the response from an asynchronous call in JavaScript, it's important to understand how JavaScript handles asynchronous operations like fetching data, reading files, or executing time-based actions. JavaScript is a single-threaded nature means it can only handle one task at a time, but it uses asynchronous programming to execute tasks without blocking the main thread.
You can manage asynchronous calls using callbacks, promises, or the async/await syntax, as well as the Promise syntax. These methods help return responses efficiently and improve the readability and maintainability of the code.
Return Response using a Callback Function
A callback is a function passed as an argument to another function, which is executed once the asynchronous operation completes. This is one of the oldest techniques to handle asynchronous code.
JavaScript
function fetchData(callback) {
setTimeout(() => {
const s = "Return Response Using a Callback Function";
callback(s);
}, 1000);
}
// Using the callback
fetchData((response) => {
console.log(response);
});
Output
Return Response Using a Callback Function
Explanation: The fetchData executes an asynchronous operation using setTimeout(), then calls the provided callback function once the data is available.
Return Response using Promises
A promise represents a future value that may not be immediately available. It provides a cleaner, more manageable way to work with asynchronous operations, allowing you to chain operations using .then() and .catch().
JavaScript
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const s = "Return Response Using Promises";
resolve(s);
}, 1000);
});
}
// Using the promise
fetchData()
.then((response) => {
console.log(response);
})
.catch((error) => {
console.error("Error:", error);
});
Output
Return Response Using Promises
Explanation: The fetchData returns a promise that resolves after 1 second. The .then() method is used to handle the resolved data, while .catch() catches any errors that may occur.
Return Response using Async/Await
Async/await is built on top of promises, having more readable and cleaner syntax that resembles synchronous code. It uses the async keyword to declare a function that returns a promise, and the await keyword to wait for the promise to resolve.
JavaScript
async function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const a = "Return Response Using Async/Await";
resolve(a);
}, 1000);
});
}
async function getData() {
try {
// Waits for the promise to resolve
const response = await fetchData();
console.log(response);
} catch (error) {
console.error("Error:", error);
}
}
getData();
Output
Return Response Using Async/Await
Explanation: The fetchData returns a promise, and getData uses await to wait until the promise is resolved. This approach makes the code look more synchronous, improving readability.