1

I've got the following code:

    router.post('/', function(req, res, next) {

        doAsyncStuff()

       .then(ret=>{
          console.log('first then block')   
          if (/*something*/)
            res.sendStatus(202); /*I want to stop the execution here. changing this in return res.sendstatus will not solve the problem*/
          else
            return doanotherAsyncStuff() /*i could move the second then block here but i need another catch statment*/  
        })

        .then(ret=>{
           console.log('second then block');
           res.sendStatus(200)
        })

        .catch(err=>{
          console.log(err)
          err.status = 503
          next(err)
        })

     });

My problem is that when my if expression is true, I want to call res.sendstatus(202) and stop the execution flow. But my code is not doing what I want, because even if my if expression is true, "second then block" is still logged.

I could move the second then block into the first one, just after the doanotherAsyncStuff() method is called, but if I do that I need another catch statement, and I'd like to have only one catch statement that is called when an error occurs in any async method called.

So my question is: is there a way to block the promise flow execution when my if expression is true?

daphtdazz
  • 7,754
  • 34
  • 54
radar155
  • 1,796
  • 2
  • 11
  • 28

2 Answers2

0

Just separate those blocks. In the if return what you want to, in the else call another function where you perform your async stuffs and you chain there the other then block, instead of having the then immediately after the first one.

And add a catch also in first then in order to catch errors also in the first promise.

quirimmo
  • 9,800
  • 3
  • 30
  • 45
0

No, you can't pick which subsequent thens to hit from within the execution of one of your callbacks.

Just do what you suggest:

    ...
    .then(ret => {
        if (/*something*/) {
            return res.sendStatus(202);
        }
        return doanotherAsyncStuff().then(function() {
            return res.sendStatus(200);
        });
    })
    .catch(err=>{
    ...

Edit You don't need an extra catch because you are returning an extra promise into the promise chain, so if it fails your existing catch will get called anyway.

daphtdazz
  • 7,754
  • 34
  • 54