I'm trying to make three requests using fetch(), each one depends on the results of the previous request. If any of the requests fail, I want to throw a custom error.
This pattern works except if the innermost request fails, it throws all three errors. If the middle request fails, it throws the middle and outer errors.
How can I fix this so it only throws the error from the level where the request fails? Is there a better way to write this?
async function requests() {
try {
let response1 = await fetch();
if (response1.ok) {
try {
let response2 = await fetch();
if (response2.ok) {
try {
let response3 = await fetch();
if (response3.ok) {
let jsonResponse3 = response3.json();
return jsonResponse3;
}
throw new Error('Request 3 failed');
} catch (error) {
console.log(error);
}
}
throw new Error('Request 2 failed');
} catch (error) {
console.log(error);
}
}
throw new Error('Request 1 failed');
} catch (error) {
console.log(error);
}
}
Try something like this.
function dummyFetch() {
return new Promise(resolve => {
setTimeout(() => {
resolve({
ok: true
})
}, 500)
})
}
async function doAllSteps() {
const response1 = await dummyFetch()
if (!response1.ok) {
throw new Error('foo')
}
const response2 = await dummyFetch()
if (!response2.ok) {
throw new Error('foo')
}
const response3 = await dummyFetch()
if (!response3.ok) {
throw new Error('foo')
}
const response4 = await dummyFetch()
if (!response4.ok) {
throw new Error('foo')
}
return 'you did it!'
}
function go() {
return new Promise((resolve, reject) => {
try {
resolve(doAllSteps())
} catch (error) {
reject(error)
}
})
}
go().then((success) => {
console.log(success)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With