JavaScript Promise Vs Callback
What are Promises in JavaScript?
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 reject
A promise can be created using Promise constructor.
var promise = new Promise(function(resolve, reject) {
const x = "dqdigitals";
const y = "dqdigitals"
if(x === y) {
resolve();
} else {
reject();
}
});
promise.
then(function () {
console.log('Success, You are a dqdigitals reader');
}).
catch(function () {
console.log('error has occurred in processing the request');
});
Output : Success, You are a dqdigitals reader
What is Callback in JavaScript ?
Callbacks are a great approach to dealing with something once another task has been finished. So a callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. This is valid in JavaScript because functions are objects and objects can be passed as arguments to functions. The basic structure of the callback function looks something like this.
const callbackFn = (firstName, callback) => {
setTimeout(() => {
if (!firstName) return callback(new Error('no first name passed in!'))
const fullName = `${firstName} Kennedy`
return callback(fullName)
}, 2000)
}
callbackFn('John', console.log)
callbackFn(null, console.log)
Here we’re using the setTimeout() function in order to make our function asynchronous. In addition to setTimeout(), other asynchronous operations you’re likely to see in the real-world are: AJAX and HTTP calls, database calls, filesystem calls (in the case of Node, if no synchronous version exists), etc.
In this function, we “reject” it if the first name argument is null. When we do pass in the firstName argument, the callback function (almost always the last argument in a callback-based function’s argument list) gets called and returns the value after the 2 seconds set in setTimeout().
Note: If we don’t pass in a callback, we get a TypeError: callback is not a function error.
Conclusion
To implement asynchronous code in JavaScript we use callback functions and promises. A callback function is passed as an argument to another function whereas Promise is something that is achieved or completed in the future. In JavaScript, a promise is an object and we use the promise constructor to initialize a promise. To use promise objects we take help from promise consumers that are then() method(if promise fulfilled) and catch() method (if promise is rejected).
We encourage our readers to treat each other respectfully and constructively. Thank you for taking the time to read this blog post to the end. We look forward to your contributions. Let’s make something great together! What do you think? Please vote and post your comments.