Monday, April 27, 2020

Javascript Promise.all : Way to perform action when Multiple Parallel enqueued Actions are Completed in Lightning Components

As we all know that all actions from Lightning components are sent to server in asynchronous manner and we can not predict the sequence about response from server.

If we have requirement to wait for all operations to complete and then perform some action on lightning components like hiding the spinner or displaying all data at once.

We can either queue the first server call and when we get response then we perform second server call. For this you can use Javascript Promise pattern to sequence the server call. Please refer below URL for complete understanding of sequencing of server call using javascript promise.

JavaScript Promises vs Callback Functions in Lightning Components

Now if we need to fire server calls in parallel and want to wait for all response, then you can utilize promise.all methods to achieve this. This will execute many promises in parallel and wait until all of them are ready. Below is syntax to use promise.all:
 
//create array of promise and pass it to promise.all 
var promiseArray =[promise1, promise2];
var combinedPromise = Promise.all(promiseArray);
//this return single promise. Now handle it with then and catch
combinedPromise
.then($A.getCallback(function(results){
 //handle success
 var promise1Results = results[0]; //Results from Promise 1
 var promise2Results = results[1]; //Results from Promise 2
})) 
.catch($A.getCallback(function () { 
 //Handle errors on any promise here
 console.log('Some error has occured'); 
}));

Note:
  • Promise.all takes an array of promises and returns a new promise.
  • The new promise resolves when all listed promises are settled, and the array of their results becomes its result.
  • Order of the resulting array members is the same as in its source promises. Even though the first promise takes the longest time to resolve, it’s still first in the array of results.
  • If any of the promises is rejected, the promise returned by Promise.all immediately rejects with that error.
  • For example, if there are multiple fetch calls and one fails, the others will still continue to execute, but Promise.all won’t watch them anymore. They will probably settle, but their results will be ignored. Promise.all does nothing to cancel them, as there’s no concept of “cancellation” in promises.
  • This will help to improve the performance of lightning components as server operations are not performed in sequential order. Due to parallel call to server, lightning components will perform better.
I have created a sample lightning component which fetch Account and Task records from server and displays it in UI only when both operations are completed and response is returned to lightning components. below is gif image displaying the lightning component functionality:


Below is complete snippet for your reference:

Hope this will help!!

15 comments:

  1. Nice article!
    I found many useful information in your blog, it was awesome to read,thanks for sharing this great content, keep sharing..
    Salesforce Support and Maintenance Services

    Its really an Excellent post.

    ReplyDelete
  2. I will really appreciate the writer's choice for choosing this excellent article appropriate to my matter.Here is deep description about the article matter which helped me more.
    360DigiTMG

    ReplyDelete
  3. A great helper for me is the writing service where I buy custom essays online because it always helps me out when I have difficulties. My student life is a pleasure for me because I have someone to help.

    ReplyDelete
  4. HOW I GO MY DESIRED XMAS LOAN AMOUNT $520,000.00 FROM A RELIABLE AND TRUSTED LOAN COMPANY LAST WEEK. Email for immediate response: drbenjaminfinance@gmail.com

    Hello everyone, Am here to testify of how i got my loan from BENJAMIN LOAN FINANCE(drbenjaminfinance@gmail.com) I don't know if you are in need of an urgent loan to pay bills, start business or build a house, they offer all kinds of loan. So feel free to contact Dr.Benjamin Scarlet Owen he holds all of the information about how to obtain money quickly and painlessly via Email: drbenjaminfinance@gmail.com

    and consider all your financial problems tackled and solved. Share this to help a soul right now, Thanks


    ReplyDelete
  5. Are you in need of Loan? Here all problem regarding Loans is solve between a short period of time what are you waiting for apply now and solve your problem or start a business with funds Contact us now. many more 2% interest rate.(Whats App) number +919394133968 patialalegitimate515@gmail.com
    Mr Sorina

    ReplyDelete
  6. Thank you for sharing this post, you have given very good information in this post so that you can understand it better in reading. weliv.onlineTo purchase any type of product, visit our site so that you can actually purchase the product.

    ReplyDelete
  7. This is most informative and also this post most user-friendly and super navigation to all posts.
    Plant Engineering Service
    3D Laser Scanning Modelling
    Reverse Engineering Cad Drawings
    Point cloud to 3D Model California

    ReplyDelete
  8. Nice and valuable information. Thanks for sharing. Also visit amazon.com for  unlimited e-commerce products.

    ReplyDelete
  9. It's just awesome. I will share this with my friends too.
    If you searching for authentic trending news articles
    Just click on:
    pakistan it companies
    advertising agencies
    company for digital marketing

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. Новейший муравьиный майнер KA3 от Bitmain - это последнее достижение в вычислительной эффективности алгоритма Kadena.Bitmain Antminer KA3 обеспечивает отличную скорость хэширования 166 тыс. хэшей в секунду, при этом энергопотребление составляет всего 3154 Вт.
    Bitmain KA3 оценивается как самый сильный майнер Blake 2s и является отличным выбором для майнинга KDA (Kadena).KA3 - это первый выбор для майнинга криптовалюты Kadena, обеспечивающий плавный и заслуживающий доверия процесс майнинга.
    Новая эволюция, скачок в производительности вычислений.KA3 обеспечивает выдающуюся производительность вычислительной мощности в 166 тонн, а новая эволюция вычислительной производительности обеспечивает значительное улучшение по сравнению с текущим выходом на рынок.bitmain ka3 купить
    Создание эффективности и отраслевых стандартов.KA3 вводит новый отраслевой стандарт эффективности 19.0 / Pioneering в новую эру энергосбережения и оптимизированной производительности.
    https://www.2140miner.ru/bitmain/Bitmain-Antminer-KA3-166Th.html

    ReplyDelete
  12. https://www.sfdcstuff.com/2020/04/javascript-promiseall-way-to-perform.html?sc=1666829953346#c4547183684639389403

    ReplyDelete
  13. Very informative. Appreciate the effort you took to write about one of the most relevant sectors right now. Software development center

    ReplyDelete