If you never need the capability to nest callbacks, your code can become difficult to debug and maintain. The following code snippet shows an example of nested callbacks (they are also commonly referred to as callback hell):
getUsers(function () {
getUserDetail(function () {
getProductsPurchasedByUser(function() {
getRecommendedProducts(function () {
});
});
});
});
The Promise API (https://developer.mozilla.Org/en-US/docs/Web/JavaScript/Guide/Using_promises) in JavaScript solves the problem of callback hell by returning the object that can attach callbacks, rather than passing the callback a the parameter.
The preceding code snippet for a nested callback can be written as follows, using the Promise API:
getUsers().then(function(userslist) {
return getUserDetail(userslist);
})
.then(function(userDetail) {
return getProductsPurchasedByUser(userDetail);
})
.then (function(productsList) {
return getRecommendedProducts(productsList)){
}
.then(function(product) {
console.log('Got the final result: ' + product);
})
.catch(failureCallback);//Handle any error
In the preceding code snippet, it is assumed that getUsers(), getuserDetail(), getProductsPurchasedByUser(), and getRecommendedProducts() are defined as Promises. To define a Promise, use the following syntax:
function getUsers(){
return new Promise(function(resolve,reject) {
if(/*resolve state*/){
resolve();
}
else {
reject();
}
});
}