+ 6
What is the difference between callback and promise in javascript?
Some real time example would better to understand.
5 Answers
+ 7
bit_byte,
Promises are functional. A promise is in a sense a function and returns, whatever is needed.
Callbacks, aren't that much functional. You request something of a function, when done, follow the callback. There may be several callbacks to follow several routes.Â
They seem to work similar. But they are conceptionally different
Have a look at the provided source to get more explanation on the differences. Hope it helpsđ
https://m.youtube.com/watch?v=ubUQfeWSYk4
Additional:
https://stackoverflow.com/questions/22539815/arent-promises-just-callbacks#22540276
+ 3
Hi @Saiful Adnan
Functions are block of code which perform some actions
Ex: function add(number1,number2){
return number1+number2;
}
Above function is used to add two numbers and return the sum
+ 2
what is function? how it work? why it used in javascript?
+ 1
Promises and Call backs both are used for Async programming,
While calling an async api, we can pass a function as parameter and once the api returns any value, that function will be executed.
Ex:
const request = require(ârequestâ);
request('https://www.somepage.com', function (error, response, body) {
if(error){
// Handle error.
}
else {
// Successful, do something with the result.
}
}); [Taken from https://bit.ly/2EmUpMp]
Cons:
1. There is no built in error catching, we have to catch the error every time a callback is made.
2. For nested async calls, we may end up writing multiple nested callback functions with multiple error handlers
These cons can be overcome by using promises
In this model, every call will return a promise and each promise is like an object that has many methods (like .then()) which we can use to call any API asynchronously.
Ex:
someAsyncOperation(someParams)
.then(function(result){
// Do something with the result
})
.catch(function(error){
// Handle error
});
For nested call backs, we can simply use cascading then methods and this would enable a much cleaner code with high readability
Just like with callback based APIs, this is still asynchronous operations. The code that is executed when the request has finishedâââthat is, the subsequent .then() callsâââis put on the event loop just like a callback function would be. This means you cannot access any variables passed to or declared in the Promise chain outside the Promise. The same goes for errors thrown in the Promise chain.
+ 1
Thank you Harikrishna