Callbacks vs Promises vs Async/Await
Last Updated :
23 Jan, 2024
Callbacks, Promises, and Async/Await are three different approaches in JavaScript for handling asynchronous operations. Let's briefly discuss each.
Callbacks are functions passed as arguments to other functions, and they are executed after the completion of a specific task. Callbacks have been a traditional way of handling asynchronous operations in JavaScript.
Note: Callbacks can lead to "callback hell" or "pyramid of doom" when dealing with multiple nested asynchronous operations, making the code harder to read and maintain.
Example: fetchUserDataWithCallback simulates fetching user data from an API and then invokes a callback (processUserData) to process the data.
JavaScript
// Callback function to process user data
function processUserData(data, callback) {
console.log("Processing user data:", data);
callback();
}
// Function to fetch user data with a callback
function fetchUserDataWithCallback(callback) {
// Simulating an API request
const userData = { id: 1, name: "John Doe" };
callback(userData);
}
// Using the callback
fetchUserDataWithCallback((data) => {
processUserData(data, () => {
console.log("User data processed successfully.");
});
});
OutputProcessing user data: { id: 1, name: 'John Doe' }
User data processed successfully. Promises were introduced to address the callback hell issue and provide a more structured way of handling asynchronous code. A Promise is an object representing the eventual completion or failure of an asynchronous operation.
Promises provide a more structured way to handle asynchronous code and simplify error handling. They can be chained using .then() and .catch().
Example: Here, fetchUserDataWithPromise returns a Promise, simulating the asynchronous nature of an API request. The .then() method handles the resolved value, and the .catch() method handles errors.
JavaScript
// Function to fetch user data with a Promise
function fetchUserDataWithPromise() {
// Simulating an API request
const userData = { id: 1, name: "John Doe" };
return new Promise((resolve, reject) => {
if (userData) {
resolve(userData);
} else {
reject("Error fetching user data.");
}
});
}
// Using the Promise
fetchUserDataWithPromise()
.then((data) => {
console.log("Processing user data:", data);
console.log("User data processed successfully.");
})
.catch((error) => {
console.error("Error:", error);
});
OutputProcessing user data: { id: 1, name: 'John Doe' }
User data processed successfully. Async/Await is a syntactic sugar built on top of Promises. It allows writing asynchronous code that looks and behaves more like synchronous code, making it easier to read and understand.
Async/Await simplifies asynchronous code by allowing the use of the await keyword to pause the execution until the Promise is resolved. It's particularly useful when dealing with multiple asynchronous operations.
Example: Here, fetchUserDataWithAsyncAwait returns a Promise, and processUserDataWithAsyncAwait is an asynchronous function that uses the await keyword to handle the resolved value.
JavaScript
// Function to fetch user data with Async/Await
async function fetchUserDataWithAsyncAwait() {
// Simulating an API request
const userData = { id: 1, name: "John Doe" };
return new Promise((resolve) => {
resolve(userData);
});
}
// Function to process user data using Async/Await
async function processUserDataWithAsyncAwait() {
try {
const data = await fetchUserDataWithAsyncAwait();
console.log("Processing user data:", data);
console.log("User data processed successfully.");
} catch (error) {
console.error("Error:", error);
}
}
// Using Async/Await
processUserDataWithAsyncAwait();
OutputProcessing user data: { id: 1, name: 'John Doe' }
User data processed successfully. Differences between Callbacks, Promises, and Async/Await:
|
Manage asynchronous
| Deliver a more robust explanation for managing asynchronous operations
| Make asynchronous code appears synchronous improve code quality
|
Less readable because of nesting or callback hell
| More readable as compare to Callbacks
| Highly readable with clean code.
|
Function-based structure
| Introduced the Promise object and methods like .then() and .catch()
| Async and Await used
|
Suitable for simple cases
| Perfect for complex asynchronous operations, managing multiple asynchronous and handle API calls
| Use to maintain code in large applications improves the code quality.
|
Normally good in performance
| Just overhead due to the promise creation
| slight overhead as Comparable to promises
|
difficult to debug
| Easier to debugging
| Streamlines debugging by letting step through debugging similar to synchronous
|
JavaScript environments
| Modern web browsers and Node.js
| Modern web browsers and Node.js
|
error handling separately
| error handling with .catch() method
| error handling using try and catch blocks
|
Similarity between Callbacks, Promises, and Async/Await:
- Callbacks, Promises, and Async/Await they all are used to handle asynchronous operations in JavaScript. All these three are designed to handle the results of asynchronous operations. i.e. similarities in asynchronous operations and handling of asynchronous results.
- They all handle errors in their own way, Callbacks use the error first convention, Promises uses the .catch() method, and Async/Await uses try and catch block.
- Callbacks, Promises, and Async/Await they all operate on the JavaScript event loop. i.e. similarity in event loop utilization.
- They all Callbacks, Promises, and Async/Await they all enable the execution of non-blocking code. This means JavaScript engines can execute other tasks/operations while waiting for an asynchronous operation to complete, they are similar in nature to Non-blocking code execution.
Similar Reads
Callbacks vs Promises vs Async/Await
Callbacks, Promises, and Async/Await are three different approaches in JavaScript for handling asynchronous operations. Let's briefly discuss each. CallbackCallbacks are functions passed as arguments to other functions, and they are executed after the completion of a specific task. Callbacks have be
5 min read
Explain Async Await with Promises in Node.js
Async/Await in Node.js is a powerful way to handle asynchronous operations. It allows you to write asynchronous code in a synchronous manner, making it easier to read, write, and debug. This feature is built on top of Promises, which represent a value that may be available now, or in the future, or
4 min read
Why is it possible to try-catch an async-await call ?
JavaScript's try-catch is used to handle errors and exceptions that occur when an error occurs during execution also called runtime error. The 'async' and 'await' are keywords in JavaScript that are used to write asynchronous code. The async keyword is used to declare an asynchronous function, which
3 min read
Promise vs Callback in JavaScript
In JavaScript, managing asynchronous operations is a key aspect of modern web development. Two popular approaches for handling these operations are Promises and Callbacks. While both techniques are designed to deal with tasks that take time to complete (like fetching data from a server), they work d
5 min read
Explain Promise.race() with async-await in JavaScript
In this article, we will try to understand how we may implement Promise.race() method with async-await in JavaScript with the help of certain coding examples as well as theoretical explanations. Let us first quickly understand how we may implement Promise.race() method. This method is one of the mos
3 min read
Explain Promise.all with async-await in JavaScript
In JavaScript, Promise.all with async-await is used to handle multiple asynchronous operations concurrently. By combining Promise.all with await, you can wait for all promises to resolve or any to reject, ensuring that all asynchronous tasks are complete before proceeding with the next code executio
4 min read
Explain Promise.any() with async-await in JavaScript
In this article, we will try to understand how to implement the Promise.any() method with async-await in JavaScript using some theoretical explanations followed by some coding examples as well. Let us firstly quickly understand the working of Promise.any() method with some theoretical examples (incl
4 min read
Async Await in Node.js
Async and await in Node are the modern way of handling asynchronous operations more efficiently. These are powerful keywords that replaces the traditional callback and Promise chaining approaches. Handling Asynchronous Operations Before Async AwaitCallbacksBefore Node version 7.6, the callbacks were
3 min read
How to use Async/Await with a Promise in TypeScript ?
In TypeScript, you can use async and await with a Promise to simplify asynchronous code and make it more readable. What is a Promise?A promise in TypeScript is an object representing the eventual completion or failure of an asynchronous operation. It acts as a placeholder for a value that may be ava
3 min read
How does await and async works in ES6 ?
In this article, we will try to understand how exactly async and await works in ES6. Let us first try to understand what exactly async and await are along with their usage and then further we will see some examples in which we would see how we may use async and await along with the normal functions.
3 min read