I’ll callback, I promise!

Tzhe’ela Trooper
2 min readJun 15, 2020

When lightning lwc annotations do not play ball.

If you worked with VisualForce for many years, your are probably painfully familiar with the idea of remote actions. Salesforce explain it nicely:

JavaScript remoting is a tool that front-end developers can use to make an AJAX request from a Visualforce page directly to an Apex controller. JavaScript remoting allows you to run asynchronous actions by decoupling the page from the controller and to perform tasks on the page without having to reload the entire page.

So the below template might already be saved in your snippets:

In LWC on the otherhand, we no longer need to use Remote Actions, and the components are designed in a VCCM model (View-Controller-Controller-Model), which removes all JS from the view. In this stack, there are several ways to make an api query:

  1. Make a HTTPS GET request from the JS controller
  2. Call an Apex method with @ AuraEnabled(cacheable=true) from the JS controller that will return the data
  3. Call an Apex method with @ AuraEnabled(cacheable=true) from the JS controller that will call the REST api for you (if you use Bearer Authorization)

In cases 1 and 3 the endpoint can be your own Org (see Remote Site settings) or an external endpoint. Checkout Invoking Callouts Using Apex for more info. Case 2 assumes that the data will be queried with SOQL or SOSL.

And like with anything in this world that can be executed through writing code, there are several ways to call an Apex method (server-side controller) from your LWC JS (client-side controller). If you want the call to be made each time a specific value changes, using the @ wire decorator, is the best option for you (don’t forget to @ track your variable). However, if you want to chain a bunch of callouts, in a similar way to the way you chained them in jQuery on the VF page, or in the Aura JS conroller ?

There are so many ways to use JS Promises in LWC, just checkout this trailhead to get an idea of a few. But I didn’t spend my evening writing this article to discuss something you can google in 5 secs. I needed to write this article so I won’t ever forget how to create the promise - callout comobo in a loop! Yes, a freaking loop. Not just any freaking loop - the most efficient loop I could find after hours of reading Q&As on the general Stackoverflow and Salesforce StackExchange. Code first, words later (if I’ll have the energy - always caveat everything!)

And dinner is ready…. so this is a WIP and the rest will be added at some point. Today’s 1% accomplished!

--

--