Promise in Lightning Web Components is very important. In LWC we call methods Asynchronous. So we don’t have much control in order of execution if we have multiple methods. Prior to promises events, callback functions were used but they had limited functionalities and created unmanageable code.
Promises are the ideal choice for handling asynchronous operations in the simplest manner. They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events. They also contain built-in mechanisms to chain one call after the other.

- Benefits of Promises
- Improves Code Readability.
- Better handling of asynchronous operations.
- A better flow of control definition in asynchronous logic.
- Error Handling is better than legacy callback.
- A Promise has four states:
- fulfilled: Action related to the promise succeeded
- rejected: Action related to the promise failed
- pending: Promise is still pending i.e not fulfilled or rejected yet
- settled: Promise has fulfilled or rejected
Syntax of Promise
var promise = new Promise(function(resolve, reject){
//do something
});
Promise constructor takes only one argument, a callback function and the Callback function takes two arguments, resolve and reject. Perform operations inside the callback function and if everything went well then call resolve. If desired operations do not go well then call reject.
You can check more details about promise here.
So now we will create an example of Promise in Lightning Web Components (LWC) to get a better idea. Here we have used Chained Promises, Promise.all(iterable), and Promise.race(iterable) to display results.
This is how our final output will look like after we complete the code flow.
So first we call the methods without Promise and we get results in random order. So to avoid that and get the result in order, we used Promise and call all methods in the chain. In the third button, we use Promise.all to complete execution only when all of the methods completed there execution. Finally, we use the race method to start next execution whenever any of the method completes its execution.
You can find the complete code on my github repo.
In my next post, we will cover the Async-Await function in Asynchronous JavaScript. Did you like the post or do you have any questions, let me know in comments. Happy Programming 🙂
1 thought on “Promise in Lightning Web Components”