An introduction to Promises

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) ...

Get Learning Salesforce Lightning Application Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.