I don't remember from where I got this stuff but might be helpful in understanding promises better.
Promises are not callbacks. A promise represents the future result of an asynchronous operation. Of course, writing them the way you do, you get little benefit. But if you write them the way they are meant to be used, you can write asynchronous code in a way that resembles synchronous code and is much more easy to follow:
ADVANTAGES
1. Readability over callbacks
2. Easy to catch errors.
3. Simultaneous callbacks
1. Readability over callbacks
Promises provide a more succinct and clear way of representing sequential asynchronous operations in javascript. They are effectively a different syntax for achieving the same effect as callbacks. The advantage is increased readability. Something like this
aAsync()
.then(bAsync)
.then(cAsync)
.done(finish);
is much more readable than the equivalent of passing each of those individual functions as callbacks, like
aAsync(function(){
return bAsync(function(){
return cAsync(function(){
finish()
})
})
});
2. Easy to catch errors.
Certainly, not much less code, but much more readable. But this is not the end. Let's discover the true benefits: What if you wanted to check for any error in any of the steps? It would be hell to do it with callbacks, but with promises, is a piece of cake:
api()
.then(function(result) {
return api2();
})
.then(function(result2){
return api3();
})
.then(function(result3){
// do work
})
.catch(function(error) {
//handle any error that may occur before this point
});
/* Pretty much the same as a try { ... } catch block.
Even better: */
api()
.then(function(result){
return api2(); })
.then(function(result2){
return api3(); })
.then(function(result3){
// do work
})
.catch(function(error) {
//handle any error that may occur before this point
})
.then(function() {
//do something whether there was an error or not
//like hiding an spinner if you were performing an AJAX request.
});
3. Simultaneous callbacks And even better:
What if those 3 calls to api, api2, api3 could run simultaneously (e.g. if they were AJAX calls) but you needed to wait for the three? Without promises, you should have to create some sort of counter. With promises, using the ES6 notation, is another piece of cake and pretty neat:
Promise.all([api(), api2(), api3()])
.then(function(result) {
//do work. result is an array containing the values of the three fulfilled promises.
})
.catch(function(error) {
//handle the error. At least one of the promises rejected.
});
Hope you see Promises in a new light now.