Created
January 16, 2024 16:53
-
-
Save prof3ssorSt3v3/2b54dc7c0d3262be2ab1aae9ea32209d to your computer and use it in GitHub Desktop.
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
//promises.js | |
document.addEventListener('DOMContentLoaded', function () { | |
getData(); | |
}); | |
function getData() { | |
let url1 = 'https://picsum.photos/id/237/300/200'; | |
let url2 = 'https://picsum.photos/id/466/300/200'; | |
let url3 = 'https://picsum.photos/id/123/300/200'; | |
let url4 = 'https://jsonplaceholder.typicode.com/todos'; | |
let badpic = 'https://picsum.photos/id/999999/300/200'; | |
let baddomain = 'https://example.org/blah'; | |
Promise.all([fetch(url1), fetch(url2), fetch(url3), fetch(url4)]) | |
.then((results) => { | |
//results is an array of responses | |
console.log(results[0], results[0].headers.get('content-type')); | |
if (!results[0].ok) throw new Error('bad image'); | |
//create an array of promises to pass to Promise.all | |
let myPromises = results.map((result) => { | |
if (result.headers.get('content-type') === 'image/jpeg') { | |
return result.blob(); | |
} else if (result.headers.get('content-type').startsWith('application/json')) { | |
return result.json(); | |
} | |
}); | |
return Promise.all(myPromises); | |
// return Promise.all([results[0].blob(), results[1].blob(), results[2].blob()]); | |
}) | |
.then((results) => { | |
//results here is an array of blobs | |
results.forEach((item) => { | |
console.log('type', typeof item); | |
console.log('constructor', item.constructor.name); | |
if (item.constructor.name === 'Blob') { | |
let img = document.createElement('img'); | |
img.src = URL.createObjectURL(item); | |
document.body.appendChild(img); | |
} else { | |
let p = document.createElement('p'); | |
p.textContent = JSON.stringify(item); | |
document.body.appendChild(p); | |
} | |
}); | |
}) | |
.catch((err) => { | |
//if even one fails | |
console.warn(err); | |
}); | |
// Promise.allSettled(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment