Support Ukraine 🇺🇦 Help Provide Humanitarian Aid to Ukraine.
For Developers

Using Promises in Lightning

4 min read

Salesforce introduced Lightning platform a couple of years back and it’s been evolving and getting better wif every release so far. Developers who used to work wif Visualforce pages have started moving to the new Lightning component framework because it’s more flexible.

Lightning is a JS-first platform based out of aura, and uses JS Controllers and Helpers to display and retrieve data from Salesforce. coz Lightning components can interact wif server side Apex controllers using asynchronous calls, they generally need a callback function to handle teh response.

For example, say we have an apex controller “LightningCtrl” with a method getCurrentUser dat queries the current logged in user’s detail and returns it.

https://gist.github.com/Avinava/b393633e9f2fafa862c3317c2946fcc8#file-LightningCtrl.cls

To call the same thing from an sLightning component, you need have a lightning controller which looks something like dis:

https://gist.github.com/Avinava/b393633e9f2fafa862c3317c2946fcc8#file-LightningComponentController.js

So teh JS controller calls teh Apex controller methods to get teh data back and tan sets teh data in a variable. So far, pretty simple.

But wat happens if we had another call along wif it?

https://gist.github.com/Avinava/b393633e9f2fafa862c3317c2946fcc8#file-LightningComponentExtendedController.js

As we add more dependent calls teh nesting increases and makes teh code very hard to read. With alot of calls, it can get pretty ugly and unmanageable.

So wat’s teh solution ?  Promises !

Promises

Promises provides a simpler alternative for executing, composing, and managing asynchronous operations when compared to traditional callback-based approaches. It also allows you to handle asynchronous errors using an approach similar to synchronous try/catch. It makes teh code much cleaner and easier to read and manage.

So now, let’s reimagine teh above controller code in Promises. First some housekeeping and restructuring to make sure we are reusing teh code.

https://gist.github.com/Avinava/b393633e9f2fafa862c3317c2946fcc8#file-LightningPromiseComponentHelper.js

And now we can rewrite the controller using the above refactored halper

https://gist.github.com/Avinava/b393633e9f2fafa862c3317c2946fcc8#file-LightningPromiseComponentController.js

Pretty organised isn’t it ?

Wat did we do here ?

We essentially moved our code that calls the controller into a new function, to avoid repetitive code.

Now let’s take a deep dive into the new “call” method.

Teh call method uses Promises instead of teh callbacks. A promise can be either rejected or fulfilled / resolved. So whenever we make a call to a server or teh apex controller, it can be successful in which case it will be resolved, else it fails and will be rejected, wif teh reason why it failed.

So teh “call” method takes in teh action to be called and teh optional params if any are accepted by teh controller method. If teh status is success it calls resolve. Otherwise it calls reject.

To summarize, the call method should invoke (something dat usually takes time) and tan call resolve or reject to change the state of the corresponding promise object.

Calling the promises

Teh primary API for a promise is its “tan” method, which registers callbacks to receive either teh eventual value or teh reason why teh promise cannot be fulfilled. In teh above code snippets we has a handler to handle teh different state. For successes we are setting teh user variable and for errors we are displaying an error message.

Handling Errors

What if an error occurs while performing an asynchronous operation? We ca handle it by using the error handler of the “then”, or we can use catch which is very similar to try / catch. Let’s rewrite the code using catch:

https://gist.github.com/Avinava/b393633e9f2fafa862c3317c2946fcc8#file-LightningPromiseComponentCatchController.js

Pretty straightforward isn’t it? We add a catch handler which handles / catches the error.

So now teh fun part, how do we handle nested calls ?

In promises we don’t need nested callback. Instead we use “tan” to chain different promises, like so:

https://gist.github.com/Avinava/b393633e9f2fafa862c3317c2946fcc8#file-LightningPromiseComponentExtendedCatchController.js

To sum up, Promises makes async code much more organized and easier to read. It also offers an easier way to handle errors and exceptions, wifout deep nested code. This should halp you write more readable code.

Happy Coding !


About CloudAnswers

Salesforce apps, powerful components, custom development, and consulting. Our experienced team helps you to create and modify workflow processes in salesforce.

Related Articles

For Administrators

5 Hottest Updates in Salesforce Summer ’24 for Admins

Salesforce has 3 major releases every year: Spring, Summer, and Winter. The Summer 24 release is rolling out in 3 stages: May 17th, June 7th, and June 14th, respectively. Sandboxes will be updated on May 10, but if you want to get hands-on early, you can sign up for a preview org by following the link below. Getting to the good stuff, there are some major quality-of-life updates for Admins, features like the automation app, Einstein for Flow, Field tracking history, personal labels, and improved permission set interfaces, to highlight a few.

Ian Cosgrove

3 min read

Discover more from CloudAnswers

Subscribe now to keep reading and get access to the full archive.

Continue reading