Created
January 16, 2024 21:46
-
-
Save prof3ssorSt3v3/1b8e20d9b4a23e0f2706a7d240682626 to your computer and use it in GitHub Desktop.
300 afternon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const url1 = 'https://picsum.photos/id/123/300/200'; //200 status | |
const url3 = 'https://picsum.photos/id/237/300/200'; //200 status | |
// const url3 = 'https://picsum.photos/id/466/300/200'; //200 status | |
const url2 = 'https://jsonplaceholder.typicode.com/posts'; //200 status | |
const url6 = 'http://127.0.0.1:5500/300/index.html'; | |
const url4 = 'https://picsum.photos/id/999999/300/200'; // 404 status | |
const url5 = 'https://example.com/bad-url'; //bad domain | |
import { AfternoonError } from './error.js'; | |
document.addEventListener('DOMContentLoaded', () => { | |
getData(); | |
}); | |
function getData() { | |
Promise.all([fetch(url1), fetch(url2), fetch(url3), fetch(url6)]) | |
.then((results) => { | |
if (!results[0].ok) throw new AfternoonError('Bad fetch call'); | |
let promiseArray = results.map((resp) => { | |
if (resp.headers.get('content-type').includes('application/json')) { | |
return resp.json(); | |
} else if (resp.headers.get('content-type').includes('image/')) { | |
return resp.blob(); | |
} else { | |
return resp.text(); | |
} | |
}); | |
return Promise.all(promiseArray); | |
//return Promise.all(results.map(resp => resp.blob())); | |
// return Promise.all([results[0].blob(), results[1].blob(), results[2].blob()]); | |
}) | |
.then((items) => { | |
items.forEach((item) => { | |
// console.log(typeof item); | |
// console.log(item.constructor.name); | |
if (item.constructor.name === 'Blob') { | |
console.log('image'); | |
let objectURL = URL.createObjectURL(item); | |
let image = document.createElement('img'); | |
image.src = objectURL; | |
document.body.appendChild(image); | |
} else if (item.constructor.name === 'Array' || item.constructor.name === 'Object') { | |
console.log('json'); | |
let p = document.createElement('p'); | |
p.textContent = JSON.stringify(item); | |
document.body.appendChild(p); | |
} else { | |
console.log('text'); | |
let p = document.createElement('p'); | |
p.textContent = item; | |
document.body.appendChild(p); | |
} | |
}); | |
}) | |
.catch(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment