-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20-Promises-Fetch-API-async-await.js
More file actions
80 lines (68 loc) · 1.92 KB
/
20-Promises-Fetch-API-async-await.js
File metadata and controls
80 lines (68 loc) · 1.92 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
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
// ---------------- PROMISE EXAMPLE ----------------
// Creating a new Promise
const myPromise = new Promise((resolve, reject) => {
// This variable decides success or failure
let success = false;
// If success is true → promise is fulfilled
if (success) {
resolve("Data received success");
}
// If success is false → promise is rejected
else {
reject("Something went wrong");
}
});
// Consuming the promise
myPromise
.then((result) => {
// Runs when promise is resolved (success)
console.log(result);
})
.catch((error) => {
// Runs when promise is rejected (error)
console.log(error);
})
.finally(() => {
// Runs no matter success or failure
console.log("Promise Completed");
});
// ---------------- FETCH API WITH PROMISES ----------------
// fetch() sends a request to the given URL
// fetch() always returns a Promise
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => {
// Convert response into JSON
// res.json() also returns a Promise
return res.json();
})
.then((data) => {
// Actual data received from the API
console.log(data);
})
.catch((error) => {
// Handles network or fetch-related errors
console.log(`Error ${error}`);
});
// ---------------- ASYNC / AWAIT EXAMPLE ----------------
console.log("async await");
// Declaring an async function
// async function always returns a Promise
async function getUsers() {
try {
// await pauses execution until fetch resolves
const res = await fetch("https://jsonplaceholder.typicode.com/users");
// Manually checking HTTP errors
if (!res.ok) {
throw new Error("API Error");
}
// Reading response body only once
const data = await res.json();
// Logging the fetched data
console.log(data);
} catch (error) {
// Handles any error inside try block
console.log(`Error: ${error}`);
}
}
// Calling the async function
getUsers();