What is the promise & Call back in javascript
I read multiple definitions for the callback and promise which confuse beginners so in this article I am giving one of them with examples.
Promise
A promise is an object which is capable to handle non-blocking events means a Promise can handle asynchronous functions in synchronous form.
How promise works:- It will work in 3 possible states.
- pending: initial state, neither fulfilled nor rejected.
- fulfilled: meaning that the operation was completed successfully.
- rejected: meaning that the operation failed.
Example:-
const pro = new Promise((resolve, reject) => {
setTimeout(function() {
resolve("Promise resolved");
}, 1000);
})
pro.then(data => {
console.log("Data->", data);
}).catch(error => {
console.log("Error->", error);
})
Callback
A callback is passed as an argument to another function so that it can be executed in that other function is called as a callback function.
Example 1:-
const callback = function(sum){
console.log("Sum of a and b =", sum);
}
function sum(a,b,callback){
let sum = a+b;
callback(sum);
}
sum(2,3, callback);
Example 2:-
const callback = function(sum){
console.log("Sum of a and b =", sum);
}
setTimeout(callback, 1000, 5);
That’s it for this time! I hope you enjoyed this post. As always, I welcome questions, notes, comments and requests for posts on topics you’d like to read. See you next time! Happy Coding !!!!!