What is difference between Callback and Promise with example
A callback is a function that is passed to an another function and also known as a higher-order function. In another words, when any function accepts another function as an argument then this contained function is called callback function.
Due to event-driven non-blocking I/O model, Node is heavy use of callbacks. A callback may or may not be executed asynchronously.Example 1:
setInterval accepts a callback function as its first parameter and also a time interval.
In the above example,
add() is a function and it is passed to function
display() as a callback.
A promise is an object which is used to handle the asynchronous result of an operation.
The promise constructor takes one argument, a callback function with two parameters, resolve and reject.
resolve()— if everything worked successfully then call resolve with result value.
reject(error)— if an error occurred then call reject with an error object like
As compared to Callback function, It is very easy to debug the error with Promise like try-catch block.
A promise made the chaining of functions straightforward and simplified the code. Common need of chaining is to execute two or more asynchronous operations back to back, making it much easier to read. Each subsequent operation starts with the result from the previous step when the previous operation succeeds.