John Estess
John Estess

Reputation: 636

Need a break or finish in Promise chain in javascript

I'm looking for a technique to drop to the last catch() on a promise chain (or a finish() or something like that - a terminal method of some sort) without having to maintain a "completed" state variable and a bogus finished() promise that I'm using now that requires the state variable to be checked after each catch and the finished() to be thrown (again). The process would be far easier to read and maintain in a chain with some sort of "drop to the last catch" method. At the moment I'm using straight ES6, but other libs will be gratefully considered.

In short how do I do this?:

begin() // some promise method
.then()
.then(/* found out I'm done here - break out or drop to last then() */)
.then()
.then()
.catch()

Upvotes: 0

Views: 1685

Answers (3)

Salman Rifai
Salman Rifai

Reputation: 126

We can break promise chain by the help of throw error

function myFunction() {
       // our custom promise or some function return promise object
       return new Promise(function(resolve,reject){
          setTimeout(function(){
            resolve('dai')
          }, 2000)
       })
    }


myFunction().then(data=>{
    console.log('main')
}).then(data =>{
    console.log('one')
}).then(data =>{
    console.log('two')
    throw new Error('custom breaked')
}).then(data =>{
    console.log('three')
}).catch(err=>{
    console.log('---------error---------')
    console.log(err.message) // custom breaked
    res.status(500).send(err.message);
})

Upvotes: 0

Damian
Damian

Reputation: 2852

You can throw an exception from then fulfillment function

var p = Promise.resolve();

p.then(() => console.log(1))
 .then(() => { console.log(2); throw 'Oh no!'; })
 .then(() => console.log(3))
 .catch(error => console.log(error));

or return a rejected promise

var p = Promise.resolve();

p.then(() => console.log(1))
 .then(() => { console.log(2); return Promise.reject('Oh no!'); })
 .then(() => console.log(3))
 .catch((error) => console.log(error));

Upvotes: 2

Eskil Fogelström
Eskil Fogelström

Reputation: 76

Shouldn't you just be able to break out of the promise chain by returning a rejected promise.

begin()
  .then(() => {
    if (/*we're done*/) {
      return Promise.reject('some reason');
    }
  })
  .then() // won't be called
  .catch() // Catch 'some reason'

Upvotes: 0

Related Questions