Skip to content

Commit e24cd77

Browse files
Promises and Async/Await
2 parents a484691 + 589adbd commit e24cd77

File tree

10 files changed

+2259
-2
lines changed

10 files changed

+2259
-2
lines changed

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ Welcome to your comprehensive JavaScript interview notes! This repository contai
1111
- [Higher Order Functions](JS-Interview-Questions/HigherOrderFunction.md)
1212
- [Map, Reduce, Filter](JS-Interview-Questions/map-reduce-filters.md)
1313
- [Polyfills](HigherOrderFunction/polyfills.html)
14-
14+
- [Promises](promises/promises.md)
15+
- [Async/Await](async-await/async-await.md)
1516
- [More Topics Coming Soon!]
1617

1718
---
@@ -41,7 +42,8 @@ Welcome to your comprehensive JavaScript interview notes! This repository contai
4142
- [Higher Order Functions](JS-Interview-Questions/HigherOrderFunction.md)
4243
- [Map, Reduce, Filter](JS-Interview-Questions/map-reduce-filters.md)
4344
- [Polyfills](HigherOrderFunction/polyfills.html)
44-
45+
- [Promises](promises/promises.md)
46+
- [Async/Await](async-await/async-await.md)
4547
---
4648

4749

async-await/async-await.js

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
2+
// 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.
3+
async function getData() {
4+
return "hello Aditya";
5+
}
6+
const dataPromise = getData();
7+
console.log(dataPromise); // Promise {<fulfilled>: 'hello Aditya'}
8+
9+
//How to extract data from above promise? One way is using promise .then
10+
dataPromise.then(res => console.log(res)); // hello Aditya
11+
12+
const p = new Promise((resolve, reject) => {
13+
resolve('Promise resolved value!!');
14+
})
15+
16+
async function getData1() {
17+
return p;
18+
}
19+
// In above case, since we are already returning a promise async function would simply return that instead of wrapping with a new Promise.
20+
const dataPromiseWithPromise = getData1();
21+
console.log(dataPromiseWithPromise); // Promise {<fulfilled>: 'Promise resolved value!!'}
22+
dataPromiseWithPromise.then(res => console.log(res)); // Promise resolved value!!
23+
/*
24+
Q: How we can use await along with async function?
25+
A: async and await combo is used to handle promises.
26+
27+
But Question is how we used to handle promises earlier and why we even need async/await?
28+
29+
*/
30+
31+
//📌 Till now we have been using Promise.then/.catch to handle promise.
32+
// Now let's see how async await can help us and how it is different
33+
34+
// The rule is we have to use keyword await in front of promise.
35+
async function handlePromise() {
36+
const val = await p;
37+
console.log(val);
38+
}
39+
handlePromise(); // Promise resolved value!!
40+
41+
// 📌 await is a keyword that can only be used inside a async function.
42+
43+
// await function() {} // Syntax error: await is only valid under async function.
44+
45+
const p0 = new Promise((resolve, reject) => {
46+
setTimeout(() => {
47+
resolve('Promise resolved value!!');
48+
}, 3000);
49+
})
50+
51+
// Let's now compare with some modification:
52+
53+
// 📌 Promise.then/.catch way
54+
function getData() {
55+
// JS engine will not wait for promise to be resolved
56+
p0.then(res => console.log(res));
57+
console.log('Hello There!');
58+
}
59+
60+
getData(); // First `Hello There!` would be printed and then after 3 secs 'Promise resolved value!!' will be printed.
61+
// 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.
62+
63+
//❓ Problem: Normally one used to get confused that JS will wait for promise to be resolved before executing following lines.
64+
65+
// 📌 async-wait way:
66+
async function handlePromise0() {
67+
// JS Engine will waiting for promise to resolve.
68+
const val = await p;
69+
console.log('Hello There!');
70+
console.log(val);
71+
}
72+
handlePromise0(); // This time `Hello There!` won't be printed immediately instead after 3 secs `Hello There!` will be printed followed by 'Promise resolved value!!'
73+
// 💡 So basically code was waiting at `await` line to get the promise resolve before moving on to next line.
74+
75+
// Above is the major difference between Promise.then/.catch vs async-await
76+
77+
//🤓 Let's brainstorm more around async-await
78+
async function handlePromise() {
79+
console.log('Hi');
80+
const val = await p;
81+
console.log('Hello There!');
82+
console.log(val);
83+
84+
const val2 = await p;
85+
console.log('Hello There! 2');
86+
console.log(val2);
87+
}
88+
handlePromise();
89+
// In above code example, will our program wait for 2 time or will it execute parallely.
90+
//📌 `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.
91+
92+
// Let's create one promise and then resolve two different promise.
93+
const p2 = new Promise((resolve, reject) => {
94+
setTimeout(() => {
95+
resolve('Promise resolved value by p2!!');
96+
}, 2000);
97+
})
98+
99+
async function handlePromise() {
100+
console.log('Hi');
101+
const val = await p;
102+
console.log('Hello There!');
103+
console.log(val);
104+
105+
const val2 = await p2;
106+
console.log('Hello There! 2');
107+
console.log(val2);
108+
}
109+
handlePromise();
110+
111+
// 📌 `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
112+
113+
114+
// Now let's reverse the order execution of promise and observe response.
115+
async function handlePromise1() {
116+
console.log('Hi');
117+
const val = await p2;
118+
console.log('Hello There! ');
119+
console.log(val);
120+
121+
const val2 = await p;
122+
console.log('Hello There! 2');
123+
console.log(val2);
124+
}
125+
handlePromise1();
126+
// 📌 `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
127+
// So in this case, both promises were resolved at different time but code execution was sequential i.e. it waited for first promise to resolve before moving on to next line of code.

0 commit comments

Comments
 (0)