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.
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.
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.
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.
Because of issues like callback hell, difficult to reason about and inversion of control promises were introduced.
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 .
It is very similar to callbacks but in a clean manner.
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.
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.
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.
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.
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).
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.
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.
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
Post a Comment