-
Notifications
You must be signed in to change notification settings - Fork 0
/
script-18_Asynchronous-JS.js
109 lines (85 loc) · 2.73 KB
/
script-18_Asynchronous-JS.js
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Using strict mode
"use strict";
console.log('\n');
const data = [
{ Name: "Oliver Queen" , Profession: "Vigilante" } ,
{ Name: "Bruce Wayne" , Profession: "Vigilante" }
];
// function getData()
// {
// setTimeout( () => {
// data.forEach( (element) => {
// console.log("Name: " , element.Name , " Profession: " , element.Profession);
// } );
// console.log('\n');
// } , 2000 );
// }
// function createData(newData)
// {
// setTimeout( () => {
// data.push(newData);
// } , 4000 );
// }
// getData();
// createData({Name: "Matt Murdock" , Profession: "Vigilante"});
// Problem in the above synchronous code:
// The getData function is executed after 2sec because the code to print the data which is the forEach function is present inside the
// callback function which is recieved by the setTimeout function along with a timer of 2sec. On the other hand ,
// The createData function is executed after 4sec because the code to push the data into the data array is present inside the
// callback function which is recieved by the setTimeout function along with a timer of 4sec.
// Because of this, the getData function is executed before the createData function and hence, we recieve the outdated data and not
// the updated data.
// Resolving the above problem using Callbacks
// function getData()
// {
// setTimeout( () => {
// data.forEach( (element) => {
// console.log("Name: " , element.Name , " Profession: " , element.Profession);
// } );
// console.log('\n');
// } , 2000 );
// }
// function createData(newData , callback)
// {
// setTimeout( () => {
// data.push(newData);
// callback();
// } , 4000 );
// }
// createData({Name: "Matt Murdock" , Profession: "Vigilante"} , getData);
// Resolving the above problem using Promises
function getData()
{
setTimeout( () => {
data.forEach( (element) => {
console.log("Name: " , element.Name , " Profession: " , element.Profession);
} );
console.log('\n');
} , 2000 );
}
function createData(newData)
{
const myPromise = new Promise( (resolve , reject) => {
setTimeout( () => {
data.push(newData);
let error = false;
if(!error)
{
resolve("Promise fulfilled !!!\n");
}
else
{
reject("Promise rejected !!!\n");
}
} , 4000 );
} );
return myPromise;
}
createData({Name: "Matt Murdock" , Profession: "Vigilante"})
.then( (response) => {
console.log("The response is: " , response);
getData();
} )
.catch( (response) => {
console.log("The response is: " , response);
} );