Asynchronous JavaScript - Part 2

Callback vs Promises vs Async Await

The word Callback, Promises, and Async Await might be intimidating to hear when you are just beginning to master JavaScript concepts. This post is here to help you have a better understanding of these functions in a short time. Now, let's begin mastering these useful concepts.

Callback Function

In Javascript every function is a first-class object, so a function is an object and can be used like any other object. This allows a function to be passed into another function as an argument, which is then invoked inside the outer function to complete an action.

      Example of a synchronous callback function.

How does it work?

We can pass functions like variables and return them in function and use them in other functions. When we pass a callback function as an argument we are passing only function definition, we are not executing the function in parameter or we aren’t passing a function with trailing function executing within parenthesis (). And since the containing function has a callback function in its parameter as a function definition, it can execute anytime.

Asynchronous Callback Function 

In this example, we are going to use the setTimeout() method to mimic the program that takes time to execute, such as data coming from the server.

The setTimeout() method executes a block of code after the specified time. Here,the greet() function is called after 2000 milliseconds( 2 seconds). During the wait, sayName('John') is executed. That is why Hello John is printed before Hello World.

The above code is executed asynchronously(the second function sayName() does not wait for the first function greet() to complete ). 

Synchronous Callback Function

    

In the above program, the code is executed synchronously. The sayName() function is passed as an argument to the greet() function.

The setTimeout() method executes the greet() function only after 2 seconds. However, the sayName() function waits for the execution of the greet() function.

Benefits of CallBack

  • CallBack functions help you write more clean and readable code. 
  • DRY — Do not repeat yourself
  • Have better maintainability

It is very important to know that callback functions can be used for 

  • Event handlers/Listeners
  • For asynchronous execution

Callback Hell 

Did you have brain freeze trying to read that piece of code ?!

CallBack Hell is when you have too many nested callbacks and it makes the code very difficult to read. When the function tree created becomes too large, the code becomes incomprehensible sometimes and is not easily refactored. Callback functions can be used for short asynchronous operations but for larger sets it is advised to use Promises. 

Let's see what Promises are in the next sub-heading 

Promises 

I promise to do this whenever that is true. If it isn't true, then I won't. 

Meme Alert !!

A promise is used to handle the asynchronous result of an operation. This sounds exactly like callbacks, but the important differences are in the usage of Promises. Instead of providing a callback, a promise has its own methods which you call to tell the promise what will happen when it is successful or when it fails. 

Promises have a few advantages over callbacks:

  • Make the async code easier to read.
  • Provide combined error handling.
  • Better control flow. You can have async actions execute in parallel or series.

The methods a promise provides are then() for when a successful result is available and catch() for when something went wrong.

A promise is an object which can be returned synchronously from an asynchronous function. It will be in one of 3 possible states:

  • Fulfilled: resolve() was called
  • Rejected: reject() was called
  • Pending: not yet fulfilled or rejected



Creating a simple promise 

A promise is created using the new keyword and its constructor that takes a callback function with two arguments. It is assumed that the code executes successfully. If the task is successful, the promise is resolved; an optional parameter “The promised task was done successfully” is passed. If the task is unsuccessful, then the promise is rejected; an optional parameter “The promised task was not done” is passed.


Promise then
The then method allows you to get notified when the asynchronous operation is done, either succeeded or failed. It takes two arguments, one for the successful execution and the other one if an error happens


Promise catch 
Promise .catch the method takes a function as an argument that handles errors if they occur. If everything goes well, the catch method is never called.

Chaining Promises
Sometimes we may need to execute two or more asynchronous operations based on the result of preceding promises. In this case, promises are chained.


Async Await 



An async function is a modification to the syntax used in writing promises. You can call it syntactic sugar over promises. It only makes writing promises easier.

Asynchronous functions contain the async keyword. You can use it in a normal function declaration


Async Functions always return a promise. If the Async function returns a value, the promise will be resolved with the value, but if the async function throws an error, the promise is rejected with that value.

Example of async function that resolves to a promise



   The above function written in promise syntax:


Both the statements will resolve to  OWASP VIT Chennai, Hence the same thing could be applied when a promise is rejected too.

Await

The await keyword is only valid inside of an async function. If used outside it will generate a SyntaxError. Awaiting on a promise, the await keyword pauses the execution of the surrounding async function until that promise is either fulfilled or rejected. await also unwraps the promise giving us access to its fulfilled value. There can be multiple await statements within a single async function.

In the below example, we declare a function that will return a promise that resolves to “OWASP VIT Chennai Student Chapter Blog” after two seconds have passed. We then declare an async function and await for the promise to be resolved before logging the message to the console.



Error handling

A useful feature of async functions is that error handling is also done synchronously. We use try-catch statements to handle our errors.
We can demonstrate this by creating a promise that will reject only some of the time.



Conclusion 

Thanks for hanging in there. Hope you understood the concepts of asynchronous Javascript and are ready to apply them in your next project. Have questions? Connect to me on LinkedIn here

0 Comments