Asynchronous javascript in Lightning Web Component

Being a scripting language, javascript can interpret only one statement at a time. With this, javscript also don't face concurrency issue like other language faces while executing threads.

Having said that, in javscript you can execute "Asynchronous Methods". These Asynchronous Methods are "Callbacks, Promises, Async/Await".


  1. Callbacks - a perfect example of callbacks in javascript is setTimeout function.


callbackDemo()
{	setTimeout(() => {
		alert('This is a callback Demo');
  }, 5000);
}

Javascript event also execute callback functions.

You can learn about event in lwc here.

2. Promises - These are used to perform asynchronous operation in javscript.


Description : A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

A promise can have three stages

- Pending - Default state, not fulfilled, not rejected.

- Fulfilled - Operation completed.

- Rejected - Operation failed.


There are 3 methods in promise promise.then(), promise.catch(), promise.finally. With these method you can also chain promises.


Syntax - >

var promise = new Promise(function(resolve, reject){
     //do something
});

Example


promiseDemo.html

promiseDemo.js

the promiseDemo method returns a Promise which will resolve in the future. When we call the promiseDemo method with 2 parameters, it will check if they are equal, if they are equal promise will resolve or else it will reject the promise.


In testPromise method when a promise is resolved or rejected it will call either .then() method (when resolved) or .catch() method (when rejected).


Every time a promise is resolved it will go in .then() block and when a promise is rejected it will go into .catch() block. Along with it you can also create .finally() block which will execute no matter what happen to promise.


In .then() or .catch() method you can chain other promise as well. Using chaining, you can execute asynchronous method in sequential order.


for example you can execute


this.promiseDemo(this.val1, this.val2)
      .then((result) => {
        alert("Resolved and Fulfilled");
        //you can execute new promise here
      })
	  .then((result)=>
	  {
		alert('You can execute new promise here');
	  })
	.catch().....


3. Async/Await - To understand async/await, you need to fully understand the concept of Promise because async/await are the extension of Promises.


Async functions - async function always returns a promise. Even if you don't return a promise explicitly, JavaScript automatically wraps it in a resolved promise and return it.


example -


 async asyncDemo() {
 return 'This is asyncDemo';
    }

 testAsync() {
 this.asyncDemo()
            .then((result) => {
 alert(result);
            });
    }

Here async method is returning a string and not returning a promise, but javscript automatically convert this to resolved promise, otherwise this.asyncDemo().then() method will generate error.

Await - await always used inside async function to wait for a promise to be fulfilled.

I have updated promiseDemo lwc component to use async/await function.


in asyncDemo function, I have used "await this.testPromise()", this will block the execution of current function until this promise fulfilled.

The output of this code will be ->


alert("Resolved and Fulfilled");
alert('This is asyncDemo');

Remember, you can't use await function inside a normal function, it can only be used inside async function.


if you want to wait for more than one promise, you can alternatively use promise.all method inside async function as follows.


await Promise.all([promise1(), promise2()]);  

The promise.all() function resolves when all the promises inside the iterable have been resolved and then returns the result.


©2019 by SFDC Blogs.