async await fetch undefined. How to handle?
Using Promise.allSettled you can run all the fetch calls in parallel and wait for them all to complete.
const test = async() => {
const promise1 = await fetch('https://dummyimage.com/48x48/4caf50/ffffff.jpg&text=.jpg')
.then(r => r.url)
const promise2 = await fetch('https://dummyimage.com/bad/url/here/48x48/e91e63/ffffff.png&text=.png')
.then(r => r.url)
const promise3 = await fetch('https://dummyimage.com/48x48/00bcd4/ffffff.gif&text=.gif')
.then(r => r.url)
const results = await Promise.allSettled([promise1, promise2, promise3])
console.log(results);
}
test();
For older support you would need to use a promise that would catch any errors from the fetch.
function makeCall () {
return new Promise((resolve) => {
fetch('https://dummyimage.com/48x48/4caf50/ffffff.jpg&text=.jpg')
.then(r => console.log(r.url))
.catch(error => resolve({ error }))
})
}
const test = async() => {
const promise1 = makeCall()
const promise2 = makeCall()
const promise3 = makeCall()
const results = await Promise.all([promise1, promise2, promise3])
console.log(results)
}
test()