Promise in LWC and JavaScript

In this post, we will implement the Promise in LWC and JavaScript. Promise in LWC works the same as it does in the simple JavaScript file. Promises is essentially a replacement for callback methods in JavaScript. If there are callbacks inside a callback and so on, it produces the issue known as Callback Hell. It makes the code extremely difficult to read and debug. The solution to this is nothing but the Promise.

What is Promise?

Promise in LWC or JavaScript is just like the promises in real life. Consider the simple scenario below:

I promise that you will have a good understanding of Promises once you read this post. The post might be good or bad and you will know it once you read the complete post, in the future. Once the promise is completed, i.e, when you read the complete post, you will get either the success value returned by the Promise, or you will get the failure reason.

Promise in JavaScript lets asynchronous methods return values like synchronous methods, instead of immediately returning the final value. A Promise is always in one of below three states:

  • pending: This is the initial state. It is neither fulfilled nor rejected.
  • fulfilled: The Promise is completed successfully.
  • rejected: The Promise is failed or there is an error.

A promise is said to be settled if it is fulfilled or rejected, but not pending.

We can perform any operation in the Promise in LWC and JavaScript, especially asynchronous operations. Then, we need to pass a function to the Promise which has two callback functions, resolve and reject. This function is also known as the executor. The Promise will perform some task and then we need to call either resolve() or reject() based on the outcome of the task. If the task is successful, call resolve() and if there is an error, call reject().

The Promise also has then(), catch(), and finally() methods to handle the Promises. If the Promise is successful and the resolve() method is called, then the then() function will execute to perform the next actions. If there is any error or if we call reject() in case of any error, the catch() method will be executed to handle the error. And in the end, finally() method will be executed regardless of the outcome of Promise.

Promise in LWC and JavaScript

Enough with the theory, let’s get into the implementation.

Consider the below Promise:

Note: You can run the below code in any JavaScript file of Lightning Web Component.

const myPromise = new Promise((resolve, reject) => {
		
	// Assuming you have completed the post, provide true or false to isGoodPost.
	// Generally we perform any asynchronous operation here.

	let isGoodPost = true;
	if(isGoodPost){
		resolve("This post was helpful");
	}else{
		reject("This post was not helpful");
	}
});

We have created a Promise in LWC and assigned it to myPromise. It accepts two parameters, resolve and reject. Based on the value of isGoodPost, we are calling either the resolve() or reject(). You can provide true or false to isGoodPost variable. We can pass anything to resolve() and reject() methods. For this demonstration, I have just passed simple Strings messages. This message will be passed to then() and catch() respectively.

And this is how you can call the Promise and handle the responses:

myPromise.then(message => {
	console.log(message);
}).catch(message => {
	console.log(message);
}).finally(() => {
	console.log("Finally Called!");
});

The then() and catch() accepts a function that has a message parameter. The message that we passed from the resolve() and reject() methods are captured in the message of then() and catch() respectively. We are just logging these messages in the console to test. In the end, we have added finally() which will execute irrespective of the Promise result.

Output

As we are passing true to isGoodPost, resolve() method will execute that will call the then() function and we will get the below output in the console.

Resolved Promise in LWC and JavaScript
Resolved Promise in LWC and JavaScript

If you are not happy with the post, assign false to isGoodPost. The reject() method will call catch() to catch the error and you will get the below output.

Rejected Promise in LWC and JavaScript
Rejected Promise in LWC and JavaScript

Also Read:

That is all from this post. We have covered the basics of Promise in LWC and JavaScript. The best part of Promise is the Chaining of Promises which solves the problem of Callback Hell. We will cover this in another post. If you don’t want to miss new implementations, please Subscribe here.

If you want to know more about Promises, you can check the below documentation: Using Promises in JavaScript.

See you in the next implementation!

Leave a Reply

Your email address will not be published. Required fields are marked *