Jonathan Zier
Jonathan Zier

Reputation: 168

Express.js sending response in promise .catch() error

I have a function that looks like this:

function x(req, res, next){

    await doSomething().catch(error =>{

        return res.send('error here'})

        }
    await doSomethingElse().catch(error =>{console.log(error)})

    return res.send('success');

}

When doSomething() returns an error, I get "Cannot set headers after they are sent to the client", which I understand, but why doesn't the script terminate when I call the first res.send?

My guess is that it's similar to a callback in that the returned value is ignored, so it sends the response, but ignores the fact that the script should end there.

How can I fix this problem?

Upvotes: 0

Views: 1247

Answers (2)

Mohammad Yaser Ahmadi
Mohammad Yaser Ahmadi

Reputation: 5051

if you want to use .then() .catch() just try:

function x(req, res, next) {
  doSomething()
    .catch((error) => {
      return res.send("error here");
    })
    .then(() => {
      doSomethingElse()
        .catch((error) => {
          console.log(error);
        })
        .then(() => {
          return res.send("success");
        });
    });
}

Upvotes: 0

jfriend00
jfriend00

Reputation: 707376

It gets very complicated to control flow when you are mixing .catch() and await. I would strongly suggest using only one model at a time. With await, you can do this:

async function x(req, res, next) {
    try {
        await doSomething();
        await doSomethingElse();
        res.send('success');
    } catch(e) {
        console.log(e);
        res.send('error here'})
    }
}

why doesn't the script terminate when I call the first res.send?

Because the return in that statement just returns back from the .catch() handler not from your main function and since you've done a .catch() and not thrown inside that catch handler or returned a rejected promise from the handler, then the parent promise because resolved and execution after the await continues just fine which then causes you to run into the second res.send() which causes the warning about headers already sent.

Upvotes: 1

Related Questions