Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Break from fetch then [duplicate]

Tags:

javascript

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(...)
like image 761
pyQueen Avatar asked Apr 07 '26 16:04

pyQueen


1 Answers

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
       }
   });
like image 106
Yousaf Avatar answered Apr 09 '26 06:04

Yousaf