Repository navigation
Expand file tree
/
Copy pathpromiseAndFetch.js
More file actions
71 lines (54 loc) · 2.14 KB
/
Copy pathpromiseAndFetch.js
File metadata and controls
71 lines (54 loc) · 2.14 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
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Success!"); // The promise is fulfilled
} else {
reject("Error occurred!"); // The promise is rejected
}
});
myPromise
.then(result => console.log(result)) // Will log "Success!" if resolved
.catch(error => console.log(error)); // Will log "Error occurred!" if rejected
// Fetch request
fetch('https://jsonplaceholder.typicode.com/todos/1') // fetch() returns a Promise
.then(response => response.json()) // Convert response to JSON (also returns a Promise)
.then(data => console.log(data)) // Log the data when the promise is resolved
.catch(error => console.log('Error:', error)); // Catch any errors
// Async awaits can handle requests more effectively
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json(); // Wait for the response to be parsed as JSON
console.log(data); // Log the data when the promise is resolved
} catch (error) {
console.log('Error:', error); // Catch any errors that occur
}
}
fetchData(); // Call the async function
// Axios streamlines the process
// npm i axios is required
const axios = require("axios");
axios.get("https://pokeapi.co/api/v2/pokemon")
.then(response => {
console.log("Data received:");
// Extracting the results array from the response
const data = response.data.results;
// Iterating over each Pokemon and logging its name
data.forEach(pokemon => {
console.log(pokemon.name);
});
})
.catch(error => {
console.error("Error fetching data:", error); // Handles any errors
});
// Interesting addition -> Promise all:
const fetchPost = fetch('https://jsonplaceholder.typicode.com/posts/1');
const fetchUser = fetch('https://jsonplaceholder.typicode.com/users/1');
Promise.all([fetchPost, fetchUser])
.then(responses => Promise.all(responses.map(res => res.json())))
.then(data => {
const [post, user] = data;
console.log('Post:', post);
console.log('User:', user);
})
.catch(error => console.log('Error:', error));