Javascript Part 2
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
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
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.
we will attach a callback function to the promise object using then to get
triggered automatically when result is ready.
// � 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!");
}
//� 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.
// 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);
});