Promise vs Callback in JavaScript
Last Updated :
20 Aug, 2024
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 differently and have distinct advantages and drawbacks. This article explores Promises and Callbacks, their benefits, and the key differences between them.
To manage asynchronous actions in JavaScript, promises are used. It is an assurance that something will be done. The promise is used to keep track of whether the asynchronous event has been executed or not and determines what happens after the event has occurred.
A Promise has four states:
- fulfilled: Action related to the promise succeeded
- rejected: Action related to the promise failed
- pending: Promise is still pending i.e. not fulfilled or rejected yet
- settled: Promise has fulfilled or rejected
Syntax:
Let promise = new Promise(function(resolve, reject){
// do something
});
A promise can be created using Promise constructor.
Parameters:
- Promise constructor takes only one argument which is a callback function (and that callback function is also referred as an anonymous function too).
- Callback function takes two arguments, resolve and reject
- Perform operations inside the callback function and if everything went well then call resolve.
- If desired operations do not go well then call reject.
Example: In this example, a Promise is created to compare two strings, ‘geeksforgeeks’ and ‘geeksforgeeks’. If the strings match, the promise resolves, logging a success message. Otherwise, it rejects, logging an error message. The then
method handles success, and the catch
method handles errors.
JavaScript
let promise = new Promise(function (resolve, reject) {
const x = "geeksforgeeks";
const y = "geeksforgeeks"
if (x === y) {
resolve();
} else {
reject();
}
});
promise.
then(function () {
console.log('Success, You are a GEEK');
}).
catch(function () {
console.log('Some error has occurred');
});
OutputSuccess, You are a GEEK
Benefits of Promises:
- Improves Code Readability
- Better handling of asynchronous operations
- Better flow of control definition in asynchronous logic
- Better Error Handling
Callbacks are a great approach to dealing with something once another task has been finished. Here, “something” refers to the execution of a function. Callbacks can be utilized if we wish to run a function immediately following the return of another function.
The type of JavaScript function is objects. They may therefore be supplied as an argument to any other function when calling them, just like any other objects (Strings, Arrays, etc.).
Example : In this example, the add
function takes two numbers, adds them, logs the result, and executes a callback function (disp
). When calling add(5, 6, disp)
, it outputs the sum and a message from the callback.
JavaScript
// The add() function is
// called with arguments a, b
// and callback, callback
// will be executed just
// after ending of add() function
function add(a, b, callback) {
console.log(`The sum of ${a}
and ${b} is ${a + b}`);
callback();
}
// The disp() function is called just
// after the ending of add() function
function disp() {
console.log(`This must be printed
after addition`);
}
// Calling add() function
add(5, 6, disp)
OutputThe sum of 5
and 6 is 11
This must be printed
after addition
Explanation:
Here are the two functions – add(a, b, callback) and disp(). Here add() is called with the disp() function i.e. passed in as the third argument to the add function along with two numbers.
As a result, the add() is invoked with 1, 2, and the disp() which is the callback. The add() prints the addition of the two numbers and as soon as that is done, the callback function is fired! Consequently, we see whatever is inside the disp() as the output below the additional output.
The benefit of Callback:
- You can run another function call after waiting for the outcome of a prior function call.
- You can call the parent function from the child function and can also pass data from child to parent.
Difference:
Properties | JavaScript Callback | JavaScript Promise |
Syntax | The syntax is difficult to understand. | The syntax is user-friendly and easy to read because of then and catch. |
Error handling | Error handling may be hard to manage. | Error handling is easier to manage using catch block. |
Callback hell | It may create callback hell. | It resolves callback hell. |
Conclusion
While both Promises and Callbacks serve the same purpose of handling asynchronous operations, Promises offer a more organized, readable, and manageable way to write code. Promises resolve the issues associated with nested callbacks and provide better error handling. As JavaScript has evolved, Promises (along with async/await) have become the preferred method for managing asynchronous logic in modern development.
How do Promises help avoid callback hell?
Promises flatten nested callback structures, making the code easier to read and manage by chaining .then() and .catch() methods instead of deeply nested functions.
What is callback hell and how do Promises resolve it?
Callback hell occurs when multiple asynchronous operations are nested within each other, leading to unreadable code. Promises resolve this by allowing flat, sequential chaining of asynchronous operations.
Can Promises be used alongside callbacks?
Yes, Promises and callbacks can be used together. For example, you can wrap a callback-based function in a Promise to take advantage of the benefits of both approaches.
How is error handling different between Promises and Callbacks?
In callbacks, error handling can be tricky, requiring manual checks. In Promises, errors are automatically caught and handled in the .catch() block, making error management easier and more reliable.
Similar Reads
JavaScript Promise Chaining
Promise chaining allows you to execute a series of asynchronous operations in sequence. It is a powerful feature of JavaScript promises that helps you manage multiple operations, making your code more readable and easier to maintain. Allows multiple asynchronous operations to run in sequence.Reduces
3 min read
How to Convert Callback to Promise in JavaScript ?
Asynchronous programming in JavaScript often involves the use of callbacks. However, callbacks can lead to callback hell and make the code harder to read and maintain. Promises provide a cleaner way to handle asynchronous operations. Converting existing callback-based code to use promises can improv
2 min read
JavaScript Callbacks
In JavaScript, callbacks play an essential role in handling asynchronous tasks like reading files, making API requests, and executing code after certain events. If youâve ever heard the phrase "I will call back later!", thatâs exactly how callbacks work. What is a Callback Function?A callback functi
5 min read
JavaScript Promise
JavaScript Promises make handling asynchronous operations like API calls, file loading, or time delays easier. Think of a Promise as a placeholder for a value that will be available in the future. It can be in one of three states Pending: The task is in the initial state.Fulfilled: The task was comp
5 min read
JavaScript Promise all() Method
The Promise.all() method in JavaScript is used for handling multiple asynchronous operations simultaneously. It takes an array (or any iterable) of promises and returns a single promise that resolves when all the input promises resolve or reject if any one of the promises fails. This makes it ideal
6 min read
JavaScript Promise catch() Method
JavaScript Promise catch() method is called whenever a promise is rejected. This method itself returns a promise so it can also be used to chain promises. This method is used for error handling. This method is mainly used after .then to chain a promise and handle reject condition. This method intern
2 min read
JavaScript Promise any() Method
JavaScript Promise any() method is a static method that takes an array of promises as a parameter and returns the first fulfilled promise. It returns a rejected value when all of the promises in the array return rejects or if the array is empty. When all the promises are rejected an AggregateError i
2 min read
JavaScript Passing parameters to a callback function
Callback FunctionPassing a function to another function or passing a function inside another function is known as a Callback Function. In other words, a callback is an already-defined function that is passed as an argument to the other code Syntax:function geekOne(z) { alert(z); }function geekTwo(a,
2 min read
What is Callback Hell in JavaScript ?
One of the primary ways to manage asynchronous operations in JavaScript is through callback functions that execute after a certain operation completes. However, excessive use of callbacks can lead to an issue known as Callback Hell, making code difficult to read, maintain, and debug. What is Callbac
4 min read
JavaScript function caller Property
The function.caller property of the JavaScript function object returns the function that invoked the specified function. It returns null if the function "f" was invoked by the top-level code in JavaScript. For functions like strict functions, async functions, and generator functions this method retu
2 min read