|
| 1 | +// ****************************** |
| 2 | +// A Better Way Fetch ****************************** |
| 3 | +// Example 1 |
| 4 | + |
| 5 | +console.log('A Better Way Fetch') |
| 6 | + |
| 7 | +// fetch('https://swapi.dev/api/planets/').then((response) => { |
| 8 | +// fetch('https://swapi.dev/api/planets9999/') |
| 9 | +// .then((response) => { |
| 10 | +// console.log(response) |
| 11 | + |
| 12 | +// // This response takes time |
| 13 | +// // console.log(response.json()) |
| 14 | +// if (!response.ok) { |
| 15 | +// console.log('ERROR NOT STATUS: 200', response.status) |
| 16 | +// } else { |
| 17 | +// response.json().then((data) => { |
| 18 | +// // console.log(data); |
| 19 | +// for (let planet of data.results) { |
| 20 | +// console.log(planet.name) |
| 21 | +// } |
| 22 | +// }) |
| 23 | +// } |
| 24 | +// }) |
| 25 | +// .catch((err) => { |
| 26 | +// console.log('SOMETHING WHEN WRONG WIT FETCH!') |
| 27 | +// console.log(err) |
| 28 | +// }) |
| 29 | + |
| 30 | +// Example 2 |
| 31 | +// Throwing error to the .catch |
| 32 | +fetch('https://swapi.dev/api/planets9999/') |
| 33 | + .then((response) => { |
| 34 | + if (!response.ok) { |
| 35 | + throw new Error(`Status Code Error: ${response.status}`) |
| 36 | + } else { |
| 37 | + response.json().then((data) => { |
| 38 | + // console.log(data); |
| 39 | + for (let planet of data.results) { |
| 40 | + console.log(planet.name) |
| 41 | + } |
| 42 | + }) |
| 43 | + } |
| 44 | + }) |
| 45 | + .catch((err) => { |
| 46 | + console.log('SOMETHING WHEN WRONG WIT FETCH!') |
| 47 | + console.log(err) |
| 48 | + }) |
| 49 | + |
| 50 | +// Compare FETCH with XMLHttpRequest() |
| 51 | +// const firstReq = new XMLHttpRequest() |
| 52 | + |
| 53 | +// firstReq.addEventListener('load', function () { |
| 54 | +// console.log('First Request WORKED!!!') |
| 55 | + |
| 56 | +// const data = JSON.parse(this.responseText) |
| 57 | +// const filmURL = data.results[0].films[0] |
| 58 | +// const filmReq = new XMLHttpRequest() |
| 59 | +// filmReq.addEventListener('load', function() { |
| 60 | +// console.log('Second Request WORKED!!!') |
| 61 | +// console.log(this); |
| 62 | +// const filmData = JSON.parse(this.responseText) |
| 63 | +// console.log('filmData: ', filmData) |
| 64 | +// }) |
| 65 | +// filmReq.addEventListener('error', function(e) { |
| 66 | +// console.log('ERROR!!', e); |
| 67 | +// }) |
| 68 | +// filmReq.open('GET', filmURL) |
| 69 | +// filmReq.send() |
| 70 | + |
| 71 | +// }) |
| 72 | +// firstReq.addEventListener('error', function () { |
| 73 | +// console.log('ERROR!!!') |
| 74 | +// }) |
| 75 | +// firstReq.open('GET', 'https://swapi.dev/api/planets/') |
| 76 | +// firstReq.send() |
| 77 | +// console.log('Request Sent!') |
0 commit comments