forked from ialimustufa/learn-js
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
day3-func.js
66 lines (52 loc) · 1.34 KB
/
day3-func.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
// asyncronous js
/**
A callback is a function that is passed as an argument to another function
and is executed after some operation has completed.
*/
function fetchData(callback) {
setTimeout(() => {
const data = 'Data fetched from server';
callback(data);
}, 2000);
}
function displayData(data) {
console.log(data);
}
fetchData(displayData); // Output after 2 seconds: Data fetched from server
// Promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve('Data fetched successfully');
} else {
reject('Error fetching data');
}
}, 2000);
});
promise
.then((data) => {
console.log(data); // Output: Data fetched successfully
})
.catch((error) => {
console.error(error); // Output: Error fetching data
});
// Async/Await
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = 'Data fetched from server';
resolve(data);
}, 2000);
});
}
async function displayData() {
try {
const data = await fetchData();
console.log(data); // Output: Data fetched from server
} catch (error) {
console.error(error);
}
}
displayData();
// mini-project: Fetch APIs