Promises with lightning web components, Explained!!!

The standard definition for promise says that Promise is the object which can produce some value in the future. These objects are used in asynchronus calls, where we can not predict time to complete the transaction. Promise helps to perform actions based on the results of the asynchronous calls.

Promises Terminology

  • Fulfilled – Indicates that the action has completed without errors
  • Rejected – Indicates that the action has failed with errors
  • Pending – Indicates that the action still is in flight

Let see the syntax below

Promise Declaration – The function declared below returns a promise. For the understanding, lets put a sample timeout in the function body.

Function makeAsyncCall(msg){ 
return new Promise((resolve, reject) => {
      setTimeout(
        () => {
          console.log(msg);
          resolve();
        }, 
        1000);
    }) 
}

Promise Execution – While calling this function in the Javascript, we can call it using the below syntax. Then segment will execute when the promise is complete, and similarly catch function will execute in the action failure.

            makeAsyncCall('msg')
            .then(result => {
                console.log('This promise is resolved')
            })
            .catch(error => {
                console.log('This promise has failed')
            });

This is so simple, but yet so powerful. Let’s see some benefits of using Promises

Chaining of Events

            makeAsyncCall('msg')
            .then(result => {
                console.log('This promise is resolved')
                // Call a new promise in here
            })
            .catch(error => {
                console.log('This promise has failed')
            });

Then block refers to the successful action on the event, we can use the same block to call another promise function inside then block. Hence you can keep chain multiple actions using promises

Error Handling

As seen in the above example, we can associate catch block with a promise. Every time an action on a promise fails, execution goes the the catch block, and statements in the catch block are implemented. We usually use some error handling or showing error toast messages in the catch block