Async Programming, Closures, IIFE
Async Programming, Closures, IIFE
function thirdTask() {
console.log("Task 3");
}
for example:-
let's say that a synchronous program performs a task that requires
waiting for a response from a remote server. The program will be stuck
waiting for the response and cannot do anything else until the response
is returned. This is known as blocking, and it can lead to an application
appearing unresponsive or "frozen" to the user.
function someLongRunningFunction() {
let start = Date.now();
while (Date.now() - start < 5000) {
// do nothing
}
return "Hello";
}
console.log('Starting...');
let result = someLongRunningFunction();
console.log(result);
console.log('...Finishing');
Problem Analysis:-
During the 5 seconds that someLongRunningFunction() is being
executed, the program will be blocked, become unresponsive, and be
unable to execute the next line of code. This can cause the program to
take a long time to complete and make the application unresponsive to
the user.
Solution:-
if the program is executed asynchronously, it will continue to run the
next line of code instructions rather than becoming blocked. This will
enable the program to remain responsive and execute other code
instructions while waiting for the timeout to complete.
Explanation:-
Callbacks
Callbacks:- An event handler is a particular type of callback. A
callback is just a function that's passed into another function, with
the expectation that the callback will be called at the appropriate
time. Callbacks used to be the main way asynchronous functions
were implemented in JavaScript.However, callback-based code can
get hard to understand when the callback itself has to call functions
that accept a callback.
Example 1:- Normal function
<script>
document.write("hey<br>");
funA();funB();</script>
How to Use a Callback Function:-
Let's say you want to plan a birthday party for your child. You
have to invite the guests, order a cake, and plan the games. But
you also want to hire a clown to entertain the guests. You can
only have the clown come to the party once all the other party
arrangements are done, and the guests have arrived.
So, you tell the clown to come to the party only after you have
notified him that the guests have arrived. In this case, the
clown represents a callback function, and the "guests arriving"
represents the function that has to complete execution before
the callback can be executed.
Example 2:-
<script>
funA("preenu",funB);
</script>
// Declare function
function fetchData(callback) {
setTimeout(() => {
const data = {name: "John", age: 30};
callback(data);
}, 3000);
}
// Execute function with a callback
fetchData(function(data) {
console.log(data);
});
console.log("Data is being fetched...");
Explanation:-
This happens when you chain multiple callbacks together, one after
the other, creating a pyramid-like structure of indentation called
callback hell, also known as the "Pyramid of Doom".
Example:-
getData(function(a) {
getMoreData(a, function(b) {
getEvenMoreData(b, function(c) {
getEvenEvenMoreData(c, function(d) {
getFinalData(d, function(finalData) {
console.log(finalData);
});
});
});
});
});
Exaplanation:-
The getData function takes a callback as an argument and is
executed after data is retrieved.
The callback function then takes the data and calls
the getMoreData function, which also takes a callback as an
argument, and so on.
Pending
Fulfilled
Rejected
Create a Promise
To create a promise object, we use the promise() constructor.
if (count) {
} else {
});
console.log(countValue);
<html><head><script>
function func1(){
setTimeout(() => {
if (!error) {
resolve();
else{
},2000);
})
func1().then(function(){
}).catch(function(error){
</script><body></body></html>
Example 3:-
<script>
function func1()
{
return new Promise(function(resolve,reject) {
setTimeout(() => {
const error = true;
if (!error) {
document.write("Function: has succesfully worked")
resolve();
}
else
{
document.write("Function: has rejected")
reject('sorry Not Worked');
}
},2000);
})
}
func1().then(function(){
document.write("Promise! Thanks for HElp")
}).catch(function(error){
document.write("Preenu! Try Again " + error)
})
</script>
Returning a Function
you can also return a function within a function.
<html>
<head>
<title>Nested functions</title>
</head>
<body>
<script>
function greet(name) {
function displayName() {
console.log('Hi' + ' ' + name);
}
// returning a function
return displayName;
}
const g1 = greet('Javascript');
console.log(g1); // returns the function definition
g1(); // calling the function
</script>
</body></html>
Explanation:-
In the above program, the greet() function is returning the displayName function definition.
Here, the returned function definition is assigned to the g1 variable. When you
print g1 using console.log(g1), you will get the function definition.
To call the function stored in the g1 variable, we use g1() with parentheses.
JavaScript Closures
In JavaScript, closure provides access to the outer scope of a function
from inside the inner function, even after the outer function has closed.
Closure is action that is inner function can have access to the outer
function variables as well as all the global variables
A closure is a function having access to the parent scope. It preserve the
data from outside.
For every closure we have three scopes:-
Local scope (OWN scope)
Outer functions scope
Global scope
Example 1:-
<html>
<head>
<title>Nested functions</title>
</head>
<body>
<script>
var i =10;
function result()
{
var j=20;
document.write(j+"<br>");
// document.write(i+"<br>");
}
result();
</script>
</body></html>
Explanation:-
Here we are accessing the variable “j” that is part of result function so that is
accessible but if we want to access the variable “I” also that would also be
accessible inside this function as it is global variable so this was a simple
example that illustrate the closure here also.
Example 2:-
<html>
<head>
<title>Nested functions</title>
</head>
<body><script>
function outerfun()
{
var j="hello im part of outer function";
document.write(j+"<br>");
function innerfun()
{
var k="im part of inner function";
document.write(k+"<br>");
//document.write(j+"<br>");
}
innerfun()
document.write(k+"<br>");
}
outerfun();
</script></body></html>
Explanation:-
Here we are having two function one is outer and one is inner so inner function
can access the variable of outer also that is closure but outer can not access
the methods and variables of inner if we will try to access them will caught
with the error.
The return statement does not execute the inner function- function is
executed only when followed by () ,but rather the return statement returns the
entire body of the function
Example 3:-
<html><head><title>Nested functions</title></head>
<body><script>
const outerfun = (a) => {
let j=10;
const innerfun = () =>
{
var k=a+j;
document.write(`the sum of two no is ${k}.`);
}
innerfun()
}
outerfun(5);
</script></body></html>
Example 4:-
<html>
<head>
<title>Nested functions</title>
</head>
<body>
<script>
// closure example
function calculate(x) {
function multiply(y) {
return x * y;
}
return multiply;
}
const multiply3 = calculate(3);
const multiply4 = calculate(4);
console.log(multiply3); // returns calculate function definition
console.log(multiply3()); // NaN
console.log(multiply3(6)); // 18
console.log(multiply4(2)); // 8
</script></body></html>
Explanation:-
In the above program, the calculate() function takes a single
argument x and returns the function definition of
the multiply() function. The multiply() function takes a single
argument y and returns x * y.
Both multiply3 and multiply4 are closures.
The calculate() function is called passing a parameter x.
When multiply3(6) and multiply4(2) are called, the multipy() function
has access to the passed x argument of the
outer calculate() function.