Using Promise for Apex Server-Side request in Lightning Component

In Lightning Components, each communication with Apex Server-Side is handled as a Javascript async request, and the callback you set is called after the server-side action is completed. A server-side action can return any JSON object, such as sObject or a map of name-value pairs.

The followoing sample code shows how a server-call works in a Lightning Component.

SampleAura.cmp

SampleAuraController.js

SampleAuraController.cls

If there have multiple requests, you need to define multiple actions and callback functions for them, then the source code may looks like below :

SampleAuraController.js

Using Promise in Javascript is a way to avoid this “Callback Hell“, and fortunately, Promise can be used in Lightning Compoenent, as below:

SampleAuraController.js

SampleAuraHelper.js

Then the source code looks more clean and more elegant, isn’t it?

More about Javascript Promise you can reference here:
https://developers.google.com/web/fundamentals/primers/promises

Enjoy it!

Related Post

Pipeline for Salesforce – Be less busy, less... Overview Pipeline is a metadata deploy app for Salesforce, supports: ・Making Changeset with Excel file in seconds. ・Exporting Pipeline target metadata list to Excel file. ・No dependencies on Salesforce Org, deploying metadata between any different organizations. ・Deploying metadata base o...
Salesforce Mass Editor (Chrome Extension) – ... This's my second Chrome Extension (First one is HERE) this year, named "Salesforce Mass Editor" and it supports for doing the below things : ・Makes any Salesforce list view to be a powerful mass editor. ・Mass insert, mass clone, mass update, mass delete, ALL-IN-ONE. Support for both Classic and ...
Salesforce Smart Importer – 1-Drag to import... This is my third Chrome Extension named Salesforce Smart Importer (Other two popular extensions are Salesforce Mass Editor and Salesforce DevTools), it is designed for Salesforce not only admin but also normal user, supports : ・1-Drag to import any Excel / CSV data on anywhere in Salesforce, both ...
Setup an awesome Salesforce developer environment ... Why Sublime Text 3 ? I've been working with Force.com for about 2 years, and always using Eclipse+Force.com IDE(See here, Eclipse Force.com IDE Installation)as my development environment. I don't think it is really difficult to use, but it could be more friendly. For example: 1. It doesn't suppo...