I am currently learning async await fetch and I've created the following example to help me learn.
The working example below:
- fetches three random json records from a Public API
- extracts the
urlfrom each returnjson - creates three
imgelements - appends three
imgelements to the document body.
Notice that promise2 has an intentionally wrong path set to force a http status 404.
How do I handle this error if it was to happen to any of the three promises?
// the big promise.
async function getAsyncData() {
try {
// attempt to resolve 3 individual unrelated promises...
let promise1 = await fetch('https://dummyimage.com/48x48/4caf50/ffffff.jpg&text=.jpg');
let promise2 = await fetch('https://dummyimage.com/bad/url/here/48x48/e91e63/ffffff.png&text=.png');
let promise3 = await fetch('https://dummyimage.com/48x48/00bcd4/ffffff.gif&text=.gif');
// we create an html img element and set its src attribute to the thumbnailUrl...
var img = document.createElement('img');
img.src = promise1.url;
// ...and add it to our html document body...
document.body.append(img);
// we create an html img element and set its src attribute to the thumbnailUrl...
var img = document.createElement('img');
img.src = promise2.url;
// ...and add it to our html document body...
document.body.append(img);
// we create an html img element and set its src attribute to the thumbnailUrl...
var img = document.createElement('img');
img.src = promise3.url;
// ...and add it to our html document body...
document.body.append(img);
} catch (error) {
console.log('Try/Catch block error:', error);
}
// return {
// }
}
getAsyncData();