‘this’ operator in JS
Closure in JS
A function is defined inside another function, and the inner function has access to the
variables and scope of the outer function. Allow for private variables and state
maintenance.
Sync in JS
Synchronous
Synchronous means the code runs in a particular sequence of instructions given in the
program. Each instruction waits for the previous instruction to complete its execution.
Asynchronous
Due to synchronous programming, sometimes important instruction gets blocked due to
some previous instructions, which causes a delay in the UI. Asynchronous code execution
allows you to execute the next instructions immediately and doesn’t block the flow.
See the output in console. If will display after two seconds.
We can write above code as:
This code does not wait for hello function but display rest result. It is called async
programming
Callbacks
A callback is a function passed as an argument to another function.
Function can’t be passed with ( ) parenthesis.
We can write above code as :
Callback Hell
Nested callbacks stacked below one another forming a pyramid structure. (Pyramid of
Doom). This style of programming becomes difficult to understand & manage.
Give some code examples of nested if, for etc.
For example we need in a sequence, first we need data of Id = 1, then id = 2, and id = 3;
But above code give data at the same time.
We can write above code as follows
This code will generate error
We resolve this can write if statement, to which whether the function is exit then call it.
We can do it for data id = 3, and 4 and so on….
this messy code is difficult to understand, so it is called callback hell.
Promises
Promise is for “eventual” completion of task. It is an object in JS.
It is a solution to callback hell.
See the return values on browser console. By writing -> promise
Promise has three states
See on console of browser, the promise will return ‘success’ message and also status –
fulfilled.
See on console of browser, the promise will return ‘rejected’ message and also status –
‘rejected’.
See the result on console, three states, pending, fulfill, and rejected
General programing is return automatically like API
How to Use Promises
these functions automatically have two parameters, which return res or err
Promise Chain
We write code one after another
We can place p2 in then block of p1
Return data one after another by following code
And refined promise chaining code
Async and Await
Async function always returns a promise
Async function myFunc(){…}
Awaits pauses the execution of its surrounding async function until the promise is settled.
It will return promise, check on console
Multiple call
Our first example
IIFE : Immediately Invoked Function Expression
IIFE is a function that is called immediately as soon as it is defined