Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4K views

Javascript Part 2

Yes javascript part 2 which has advance level
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4K views

Javascript Part 2

Yes javascript part 2 which has advance level
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

JAVASCRIPT PART 2

Callback
i. Good Part of callback - Callback are super important while writing asynchronous code in
JS
ii. Bad Part of Callback - Using callback we can face issue:
o Callback Hell

Understanding of Bad part of callback is super important to


learn Promise in next lecture.
Note:- Javascript is synchronus single threaded language . it can just do
one thing at a time. Which means javascript will not wait for anyone .
whatever you give to javascript it execute quickly it does not wait.

But what if we have to delay execution of any line, we could utilize


callback, How?
Assume a scenario of e-Commerce web, where one user is placing
order, he has added items like, shoes, pants and kurta in cart and now
he is placing order. So in backend the situation could look something
like this.

Assumption, once order is created then only we can proceed to payment, so there
is a dependency. So How to manage this dependency. Callback can come as
rescue, How?

To make it a bit complicated, what if after payment is done, you have to show
Order summary by calling api.showOrderSummary() and now it has dependency
on api.proceedToPayment() Now my code should look something like this:
When we have a large codebase and multiple apis and have dependency on each
other, then we fall into callback hell. These codes are tough to maintain. These
callback hell structure is also known as Pyramid of Doom.

Till this point we are comfortable with concept of callback hell but now
lets discuss about Inversion of Control. It is very important to understand
in order to get comfortable around the concept of promise.

Inversion of control is like that you lose the control of code when we are using
callback.

Promises
Promises are used to handle async operations in JavaScript. We will discuss with
code example that how things used to work before Promises and then how it works
after Promises Suppose, taking an example of E-Commerce

Now, we will make createOrder function return a promise and we will


capture that promise into a variablePromise is nothing but we can assume
it to be empty object with some data value in it, and this data value will
hold whatever this createOrder function will return.
Since createOrder function is an async function and we don't know how much time
will it take to finish execution.

So the moment createOrder will get executed, it will return you a undefined value.
Let's say after 5 secs execution finished so now orderId is ready so, it will fill
the undefined value with the orderId.

In short, When createOrder get executed, it immediately returns a promise


object with undefined value. then javascript will continue to execute with
other lines of code. After sometime when createOrder has finished
execution and orderId is ready then that will automatically be assigned to
our returned promise which was earlier undefined

Question is how we will get to know response is ready?,

we will attach a callback function to the promise object using then to get
triggered automatically when result is ready.

Promise Object are immutable.


-> Once promise is fulfilled and we have data we can pass here and there and we
don't have to worry that someone can mutate that data. So over above we can't
directly mutate user promise object, we will have to use .then
async await
Async is a keyword that is used before a function to create a async function.
async function always returns a promise, even if I return a simple string from
below function, async keyword will wrap it under Promise and then return.

Another example where async function is returning a Promise

Q: How we can use await along with async function?


async and await combo is used to handle promises. await is a keyword
that can only be used inside a async function.
const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise resolved value!!");
}, 3000);
});

// Let's now compare with some modification:

// � Promise.then/.catch way
function getData() {
// JS engine will not wait for promise to be resolved
p.then((res) => console.log(res));
console.log("Hello There!");
}

getData(); // First `Hello There!` would be printed and then after 3


secs 'Promise resolved value!!' will be printed.
// Above happened as Javascript wait for none, so it will register
this promise and take this callback function and register separately then
js will move on and execute the following console and later once promise
is resolved, following console will be printed.

//� Problem: Normally one used to get confused that JS will wait for
promise to be resolved before executing following lines.

// � async-wait way:
async function handlePromise() {
// JS Engine will waiting for promise to resolve.
const val = await p;
console.log("Hello There!");
console.log(val);
}
handlePromise(); // This time `Hello There!` won't be printed
immediately instead after 3 secs `Hello There!` will be printed followed
by 'Promise resolved value!!'
// � So basically code was waiting at `await` line to get the
promise resolve before moving on to next line.

// Above is the major difference between Promise.then/.catch vs


async-await

//� Let's brainstorm more around async-await


async function handlePromise() {
console.log("Hi");
const val = await p;
console.log("Hello There!");
console.log(val);

const val2 = await p;


console.log("Hello There! 2");
console.log(val2);
}
handlePromise();
// In above code example, will our program wait for 2 time or will
it execute parallely.
//� `Hi` printed instantly -> now code will wait for 3 secs -> After
3 secs both
// promises will be resolved so
//('Hello There!' 'Promise resolved value!!' 'Hello There! 2'
'Promise resolved value!!')
//will get printed immediately.

// Let's create one promise and then resolve two different promise.
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise resolved value by p2!!");
}, 2000);
});

async function handlePromise() {


console.log("Hi");
const val = await p;
console.log("Hello There!");
console.log(val);

const val2 = await p2;


console.log("Hello There! 2");
console.log(val2);
}
handlePromise();
// � `Hi` printed instantly -> now code will wait for 3 secs ->
//After 3 secs both promises will be
// resolved so ('Hello There!' 'Promise resolved value!!' 'Hello
There! 2' 'Promise
//resolved value by p2!!') will get printed immediately.
//So even though `p2` was resolved after 2 secs it had to wait for
`p` to get resolved

// Now let's reverse the order execution of promise and observe


response.
async function handlePromise() {
console.log("Hi");
const val = await p2;
console.log("Hello There!");
console.log(val);

const val2 = await p;


console.log("Hello There! 2");
console.log(val2);
}
handlePromise();
// � `Hi` printed instantly -> now code will wait for 2 secs ->
// After 2 secs ('Hello There!' 'Promise resolved value by p2!!')
will
//get printed and in the subsequent second i.e. after 3 secs
//('Hello There! 2' 'Promise resolved value!!') will get printed

Async await vs Promise

What one should use? async-await is just a syntactic sugar around


promise. Behind the scene async-await is just promise. So both are same,
it's just async-await is new way of writing code. async-await solves few of
the short-coming of Promise like Promise Chaining. async-await also
increases the readability. So sort of it is always advisable to use async-
await.

You might also like