Episode 8: Asynchronous JavaScript & Promises | How & Where to Use it in Lightning Web Component | #Salesforce


JavaScript is single threaded, which means that only one function can run at a time. If you've been doing JavaScript asynchronous development for a few years, then you may have come across one or more libraries that implemented some kind of promise pattern. A promise is basically a promise to return something at a later time. Either the thing you wanted is returned, or an error. ES6 introduced promises natively to JavaScript in the form of a Promise object. The most important advantage is how easy it is to chain asynchronous functions together.


Let’s understand it by an example-


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
function doSomething(msg){ 
  return new Promise(
    function (resolve, reject) {
      setTimeout(
        function () {
          console.log(msg);
          resolve();
        }, 
        1000);
    }); 
}
    
doSomething("1st Call")
  .then(function() {
    return doSomething("2nd Call");
  })
  .then(function() {
    return doSomething("3rd Call");
});    


The cool thing here is how the doSomething function is called. We can now use the then method to specify what gets called only after the first function completes.


If you remember we discussed arrow function in one of the previous video, by combining promises with arrow functions, the code becomes even easier to read.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function doSomething(msg){ 
  return new Promise((resolve, reject) => {
      setTimeout(
        () => {
          console.log(msg);
          resolve();
        }, 
        1000);
    }) 
}
    
doSomething("1st Call")
  .then(() => doSomething("2nd Call"))
  .then(() => doSomething("3rd Call"));  

And to see what happens when calling the reject method, we need to add some code in the setTimeout handler that intentionally throws an error.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
function doSomething(msg){ 
  return new Promise((resolve, reject) => {
      setTimeout(
        () => {
          try {
            throw new Error('bad error');
            console.log(msg);
            resolve();
          } catch(e) {
            reject(e);
          }
        }, 
        1000);
    }) 
}
    
doSomething("1st Call")
  .then(() => doSomething("2nd Call"))
  .then(() => doSomething("3rd Call"))
  .catch(err => console.error(err.message));  

You can call the failure function with each then call as well but calling the error function at the bottom of the chain using the catch method is a best practice since it catches all errors produced from the chain.


The latest release introduced async functions and a different way of calling native promises. The structure of the promise remains the same, but what changes is how the promise is called. The async call will be now using async and await keywords, and as result it will return the resolved or rejected value. 

For example let try it in the play code


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
async function doSomethingManyTimes() {
  try {
    await doSomething("1st Call");
    await doSomething("2nd Call");
    await doSomething("3rd Call");
  } catch (e) {
    console.error(e.message);
  }
}
      
doSomethingManyTimes();  

Many developers think this syntax is easier to read and understand. It resembles the top-down approach that you see in traditional synchronous code. But really, it's just a different way of working with promises.


Checkout complete video below

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

Post a Comment

0 Comments