forked from rohan-paul/Awesome-JavaScript-Interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetTimeout-basic-examples-async.js
More file actions
executable file
·51 lines (39 loc) · 1.18 KB
/
Copy pathsetTimeout-basic-examples-async.js
File metadata and controls
executable file
·51 lines (39 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// What would be the output of the below code
console.log("Paul1")
let a2 = () => {
setTimeout(() => {
console.log("inside setTimeout")
}, 500)
}
a2()
console.log("Paul2")
let a3 = new Promise(() => {})
console.log(a3)
/* Output -
Paul1
Paul2
Promise { <pending> }
inside setTimeout
EXPLANATION - I got the Promise printed event before setTimeout is because, while a2() and the a3 Promise will be run asynchronously in the Event Loop, the line < console.log(a3) > is running in the main thread and it will print what a3 is which is a Pending Promise
And note some fundamentals of Promise - When you create a new Promise, you're really just creating a plain old JavaScript object. This object can invoke two methods, then, and catch.
*/
// And now if I resolve the Promise immediately
console.log("Paul1")
let a2 = () => {
setTimeout(() => {
console.log("inside setTimeout")
}, 500)
}
a2()
console.log("Paul2")
let a3 = new Promise((resolve, reject) => {
// console.log("Resolved immediately without condition");
resolve("Resolved immediately without condition")
})
console.log(a3)
/* Output -
Paul1
Paul2
Promise { 'Resolved immediately without condition' }
inside setTimeout
*/