I'm looking for a possibility to break from a fetch-then-block. In particular: I want to test a condition and if it's true, the next 'then' should not be executed. Is that possible?
fetch(url).then(response => {
return response.text();
}).then(text => {
if (condition) {
break
}
}).then(...)
You could throw an error from the callback function of the then() method.
Throwing an error will reject the Promise returned by the then() method and will cause the callback function of the catch() method to execute instead of the next then() method(s).
fetch(url)
.then(response => response.text())
.then(text => {
if (condition) {
throw new Error('promise chain cancelled');
}
})
.then(...)
.catch(error => console.log(error));
Ideally, you should throw an error with some custom name or error code that you can use in the catch block to detect whether the error was thrown because of the condition being true.
fetch(url)
.then(response => response.text())
.then(text => {
if (condition) {
const error = new Error('promise chain cancelled');
error.name = 'CancelPromiseChainError';
throw error;
}
})
.then(...)
.catch(error => {
if (error?.name == 'CancelPromiseChainError') {
// code to run when promise chain is cancelled
}
});
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