Skip to main content

Callbacks,Promises,Async Await and Closure in JavaScript.

This weeks blog will be including about callbacks and issues of it,promises which was used to overcome the issues of callbacks and closure in JavaScript.

Callbacks, promises and async await All theses ways are used to deal with asynchronous data. By default, JavaScript programs run using a single thread. Though there are ways to create new threads, JavaScript is considered as single threaded language. JavaScript does not wait for I/O operations to get completed, instead it continues the execution of the program. This is called as non-blocking I/O. So that JavaScript is an asynchronous programming language because of this NIO nature.

Callbacks, Promises and Async Await.


As an example when a request is made to a server it will take couple of seconds to response
with the relevant data, therefore you do not want to stall your program till the data is returned.
You must keep on going or doing something where callbacks come in.

Extra facts.
until es6 => callbacks were used
es2015 (es6) => promises
es7 =>async awaits


Sometimes it is beneficial that the code is executed after something has happened. This is simply known as asynchronous. With the help of callbacks this can be achieved.

Callbacks.

This is a function that is invoked after something happens. Therefore callbacks depends on something happening.In callbacks simply a function is passed into another function. The passed function is call-backed after something has occurred because JavaScript allows higher-order functions. It is a design pattern that solve the asynchronous problem but not in the best way.

Example for Callbacks.

setTimeOut()

Callbacks  'setTimeOut'   takes a callback function and a certain amount of time in milliseconds (Delay time). When the function is called it starts the counting and then execute the function and it uses a call back.

Prints this is a log when the function is executed.

After 3 seconds of delayed time "The function was call backed." it will be printed.


Event listeners are a very common application of callbacks. Until an event occurs nothing will be happened.
ex: clicking on a button - so that a function is passed to an event listener when the event occurs it call backs the function. Function will be call-backed when ever a click event is happened in the specific button.

Before clicking ''Hello World".


After clicking "Hello World".


Because of issues like callback hell, difficult to reason about and inversion of control promises were introduced.

Promises.


Promises provide a powerful async pattern in JavaScript. Many APIs use promises. It is a JavaScript object. This object represent eventual completion or failure of an asynchronous operation and also it provides a resulting value.

Promise in JavaScript is that it commits to do something which has two results. Either
the promise is completed(resolved) or the promise is failed and it is rejected. There are two  method used in a promise .

  • '.then()' will be revokes when the promise is resolved.


  • '.catch()' is used to catch an error if the promise is rejected.

It is very similar to callbacks but in a clean manner.

Promises.


Promises are very useful when it takes along time in the background such as downloading
an image from a different server and to do something after it is completed instead of
making everything else wait for it. It also can be catched to see if it is failed and give the user an error message.

As soon as the program is executed.


After 3 seconds  ''The Success"  message and " The amount " is printed.

Handling multiple promises together.


This example includes three simple promises that always resolve. And think of scenario where you have to run all three promises parallel so that we do not have to worry for waiting for one before we start the next. 'Promise.all()' can be used and we can send all the promises that we need to run parallel (as an array) as a parameter inside to the all() method. As soon as it is done it will call  '.then()'  and '.catch()'  depending on the result resolve or rejected. In this scenario it will resolve and the parameter message will take all the resolve messages as an array.

Using  'Promise.all()' handling all the three promises.



Promise.race()


Promise.race() act as just like Promise.all() instead of waiting for all the promises to complete ,
as soon as the first promise is completed. Therefore it will return a single message
other than returning all the three messages.

Using  'Promise.race()' handling all the three promises.


fetch()


When HTTP request are needed to be made inside JavaScript there are variety of different options.
Using fetch is one way. 'fetch()' returns a promise. It takes the request as the parameter.
we must use two '.then()' methods.
In the first '.then()' it will format to a JSON object and the second '.then' will return the data.

Using fetch()

Async Await.


If we are using async await the function must use the keyword 'async' to use 'await'
inside the function body. 'await'  waits for an asynchronous process to be completed (the promise to resolve).

Async Await.

Closure


Closure is closely related to scope. JavaScript uses the functional scope. Scope refers
to the rules that determine where within the program variables and functions are accessible.

A closure is the local variables for a function - kept alive after the function has returned. Codes are executed outside the scope while having the access to the scope. In simple terms a function having access to parent scope, even after the parent function is closed. This is a combination of this environment and inner function.

Closure using Callbacks.

In this example callback function closures over the scope of  'getAddition'  and continue to have access to it.

Closure using Callbacks.

After 5 seconds of delayed time the addition will be printed.


In closure a function will be returned from another function. Closure is used to encapsulate variables into a function and restrict access to the function from the outside.
































Comments

Popular posts from this blog

Basic concepts on NodeJs

Usecases of NodeJS. Walmart and ebay. Node is not the best platform for CPU intensive heavy computational applications. But it is ideal for building fast and scalable network applications.  NodeJS is capable of handling a huge number of simultaneous connections with high throughput. For each connection NodeJS does not spawn new Thread causing max out of memory instead handle all in single thread using non-blocking I/O model. Using this architecture NodeJS has achieved over 1 Million concurrent connections. Bubbling errors up to NodeJS core event loop will cause crashing the entire program. Netflix and Uber. NodeJs is best for, I/O bound applications. Data streaming applications. Data intensive real-time applications. JSON APIs based applications. Single page applications. Modules in NodeJS. In order  a design to be reliable and maintainable should avoid defining variables and functions in the global scope. Instead we can use modular...

RESTful API

Routers can be created according to REST principles such as get, post, put, delete etc..  GET  =>  get request to r etrieve data from database or data store(An array). POST  =>  post request to insert   data to database or data store(An array). PUT  =>  put request to update the data in database or data store(An array). DELETE  =>  delete request to delete data in database or data store(An array). Creation of routers. In this scenario I have created a schema call users using mongoose.  using mongoose the created users model is retrieved. GET request  using the keyword  " get"   the data can be retrieved.  retrieving all the users in the database. By giving a parameter in the url we can get information according to the given subject.  user is retrieved according to the _id. POST request  using the keyword  "pos t"   the...