Skip to content

Commit dae0023

Browse files
committed
async await basic mechanism
1 parent 4e89ec1 commit dae0023

5 files changed

+170
-74
lines changed

Promise-Async-Await-Sequential-Execution/Promise-async-await-master-notes/calback-hell-resolved-with-promise.js

+49-56
Original file line numberDiff line numberDiff line change
@@ -4,84 +4,77 @@ Here I defined a method named addOneTo that takes a number and returns number+1
44
This is a simplified example, usually, I/O or time-consuming tasks are done using callbacks. Anyways we defined this method and then called it and got the result through the callback.
55
*/
66

7-
addOneToNum = (number, callback) => {
8-
let result = number + 1;
9-
if (callback) {
10-
callback(result);
11-
}
7+
addOneToNum = (number, callback) => {
8+
let result = number + 1
9+
if (callback) {
10+
callback(result)
11+
}
1212
}
1313

14-
addOneToNum(5, (res) => {
15-
console.log(res);
16-
})
14+
addOneToNum(5, res => {
15+
console.log(res)
16+
})
1717

18-
// Output will be 5 + 1 = 6. But what if I want to add 5 times, one to 5 using the addOneTo method. Meaning the result of the first time's addition will be feeded as input for the second time's addition. Then the result of the second time's addition will be feeded as input to the third time's addition and so on.
18+
// Output of the above will be 5 + 1 = 6. But what if I want to add 5 times, one to 5 using the addOneTo method. Meaning the result of the first time's addition will be feeded as input for the second time's addition. Then the result of the second time's addition will be feeded as input to the third time's addition and so on.
1919

20-
addOneToNum(5, (res1) => {
21-
addOneToNum(res1, (res2) => {
22-
addOneToNum(res2, (res3) => {
23-
addOneToNum(res3, (res4) => {
24-
addOneToNum(res4, (res5) => {
25-
console.log(res5);
26-
})
27-
})
20+
addOneToNum(5, res1 => {
21+
addOneToNum(res1, res2 => {
22+
addOneToNum(res2, res3 => {
23+
addOneToNum(res3, res4 => {
24+
addOneToNum(res4, res5 => {
25+
console.log(res5)
2826
})
27+
})
2928
})
30-
})
29+
})
30+
})
3131

3232
// Output will be - 5 + 1 + 1 + 1 + 1 + 1 = 10 And this is huge callback hell.
3333

34-
3534
/* Now, deal with this hell with Promises. In promises, I instead of calling the callback with the result, I return a promise that I am going to get you a result in future. So define the addOneToNum method with Promise. */
3635

3736
addOneToNumPromise = (number, callback) => {
38-
let result = number + 1;
39-
return new Promise ((resolve, reject) => {
40-
resolve(result);
41-
}
42-
)
37+
let result = number + 1
38+
return new Promise((resolve, reject) => {
39+
resolve(result)
40+
})
4341
}
4442

45-
46-
addOneToNumPromise(5)
47-
.then(res => console.log(res)
48-
)
43+
addOneToNumPromise(5).then(res => console.log(res))
4944
// Output 5 + 1 = 6
5045

5146
/* A promise is an object that is returned immediately but the result arrives later in future. Promise takes a method with two arguments, resolve and reject. resolve is called when we have a result and reject is called when we have an error. This promise object returned has two methods, then and catch. then gets the result which was raised through the resolve method. catch gets the error thrown with the reject method. Using promises we can chain our asynchronous call in a synchronous manner. */
5247

53-
addOneToNumPromise(5)
54-
.then(res1 => {
55-
return addOneToNumPromise(res1)
56-
})
57-
.then(res2 => {
58-
return addOneToNumPromise(res2)
59-
})
60-
.then(res3 => {
61-
return addOneToNumPromise(res3)
62-
})
63-
.then(res4 => {
64-
return addOneToNumPromise(res4)
65-
})
66-
.then(res5 => {
67-
console.log(res5);
68-
})
69-
48+
addOneToNumPromise(5)
49+
.then(res1 => {
50+
return addOneToNumPromise(res1)
51+
})
52+
.then(res2 => {
53+
return addOneToNumPromise(res2)
54+
})
55+
.then(res3 => {
56+
return addOneToNumPromise(res3)
57+
})
58+
.then(res4 => {
59+
return addOneToNumPromise(res4)
60+
})
61+
.then(res5 => {
62+
console.log(res5)
63+
})
7064

7165
// More compact version of the above
7266

7367
addOneToNumPromise(5)
74-
.then(res1 => addOneToNumPromise(res1))
75-
.then(res2 => addOneToNumPromise(res2))
76-
.then(res3 => addOneToNumPromise(res3))
77-
.then(res4 => addOneToNumPromise(res4))
78-
.then(res5 => console.log(res5));
79-
68+
.then(res1 => addOneToNumPromise(res1))
69+
.then(res2 => addOneToNumPromise(res2))
70+
.then(res3 => addOneToNumPromise(res3))
71+
.then(res4 => addOneToNumPromise(res4))
72+
.then(res5 => console.log(res5))
8073

8174
// Even more compact version and what a great beauty
8275
addOneToNumPromise(5)
83-
.then(addOneToNumPromise)
84-
.then(addOneToNumPromise)
85-
.then(addOneToNumPromise)
86-
.then(addOneToNumPromise)
87-
.then(console.log);
76+
.then(addOneToNumPromise)
77+
.then(addOneToNumPromise)
78+
.then(addOneToNumPromise)
79+
.then(addOneToNumPromise)
80+
.then(console.log)

Promise-Async-Await-Sequential-Execution/Promise-async-await-master-notes/callback-hell-examples.js

+35-18
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,45 @@
1+
setTimeout(
2+
changeMaker => {
3+
let list = changeMaker + ", "
14

2-
setTimeout((changeMaker) => {
3-
let list = changeMaker + ', ';
5+
setTimeout(
6+
changeMaker => {
7+
list += changeMaker + ", "
48

5-
setTimeout((changeMaker) => {
6-
list += changeMaker + ', ';
9+
setTimeout(
10+
changeMaker => {
11+
list += changeMaker + ", "
712

8-
setTimeout((changeMaker) => {
9-
list += changeMaker + ', ';
13+
setTimeout(
14+
changeMaker => {
15+
list += changeMaker + ", "
1016

11-
setTimeout((changeMaker) => {
12-
list += changeMaker + ', ';
13-
14-
setTimeout((changeMaker) => {
17+
setTimeout(
18+
changeMaker => {
1519
list += changeMaker
1620

17-
console.log(list);
18-
}, 1, 'Travis Kalanick');
19-
}, 1, 'MarkZuckerberg');
20-
}, 1, 'SteveWoz');
21-
}, 1, 'SteveJobs');
22-
}, 1, 'BillGates');
23-
21+
console.log(list)
22+
},
23+
1,
24+
"Travis Kalanick",
25+
)
26+
},
27+
1,
28+
"MarkZuckerberg",
29+
)
30+
},
31+
1,
32+
"SteveWoz",
33+
)
34+
},
35+
1,
36+
"SteveJobs",
37+
)
38+
},
39+
1,
40+
"BillGates",
41+
)
2442

2543
/* Looking at the above, setTimeout gets a callback function that executes after one millisecond. The last parameter just feeds the callback with data, i.e the argument 'changeMaker' . This is like an Ajax call except the return 'changeMaker' parameter would come from the server.
2644
2745
I am gathering a list of changeMakers through asynchronous code. Each callback gives me a single 'changeMaker' name and I append that to the list. */
28-
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/* What should this code output? A simple guess would be that it would output “I’m an async function”. However, running the code, this is what we see:
2+
3+
Promise { 'I am async' }
4+
5+
*/
6+
7+
const asyncFunc = async () => {
8+
return "I am async"
9+
}
10+
11+
// console.log(asyncFunc()) // Promise { 'I am async' }
12+
13+
/* So an Async function, just like the then function, wraps its return value inside a Promise. In other words, an Async function is just as we did before, a function that returns a Promise. It can therefore be subscribed to: */
14+
15+
// console.log(asyncFunc().then(res => res)) // => Promise { <pending> }
16+
// asyncFunc().then(res => console.log(res)) // => I am async
17+
18+
const getValueFromAsync = async () => {
19+
const value = await asyncFunc()
20+
console.log(value)
21+
return value // Note this will print Promise { <pending> } - Because this line is in the main execution thread of the function, and will get executed before the asynchronous Promise thread (run in Event Loop). And when it get executed the variable 'value' is still a Pending Promise
22+
}
23+
24+
console.log(getValueFromAsync())
25+
26+
/* OUTPUT - Why I got Promise { <pending> } - explanataion above
27+
28+
Promise { <pending> }
29+
I am async
30+
31+
32+
*/
33+
34+
/* Further Reading
35+
[https://medium.com/@jeremievandersande/javascript-from-callback-hell-to-async-await-80aebb552cc9](https://medium.com/@jeremievandersande/javascript-from-callback-hell-to-async-await-80aebb552cc9) */
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ const doRequest = async uris => {
2323
const urls = [
2424
"https://jsonplaceholder.typicode.com/posts/1",
2525
"https://jsonplaceholder.typicode.com/posts/2",
26+
"https://jsonplaceholder.typicode.com/posts/3",
27+
"https://jsonplaceholder.typicode.com/posts/4",
2628
]
2729

2830
doRequest(urls)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
const axios = require("axios")
2+
3+
const urls = [
4+
"https://jsonplaceholder.typicode.com/posts/1",
5+
"https://jsonplaceholder.typicode.com/posts/2",
6+
"https://jsonplaceholder.typicode.com/posts/3",
7+
"https://jsonplaceholder.typicode.com/posts/4",
8+
]
9+
10+
const rateLimitReq = urls => {
11+
urls.map((e, i) => {
12+
setTimeout(() => {
13+
axios
14+
.get(e)
15+
.then(response => {
16+
console.log(response.data)
17+
})
18+
.catch(console.log)
19+
}, 500 * i)
20+
})
21+
}
22+
23+
/* OUTPUT-
24+
25+
{ userId: 1,
26+
id: 1,
27+
title:
28+
'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
29+
body:
30+
'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto' }
31+
{ userId: 1,
32+
id: 2,
33+
title: 'qui est esse',
34+
body:
35+
'est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla' }
36+
{ userId: 1,
37+
id: 3,
38+
title:
39+
'ea molestias quasi exercitationem repellat qui ipsa sit aut',
40+
body:
41+
'et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut' }
42+
{ userId: 1,
43+
id: 4,
44+
title: 'eum et est occaecati',
45+
body:
46+
'ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit' }
47+
48+
49+
*/

0 commit comments

Comments
 (0)