Search code examples
node.jscallbackresponseknex.js

Catch is executed when .then operation is successful


db('fruit').where('fruit_name', 'apple')
    .then(data => {
      if (data.length === 0) {
        db('fruit').insert({
          amount: '2'     //just for this post
        })
          .then(res.sendStatus(200))
          .catch(res.sendStatus(500));
      }
      else {
        db('fruit').where('fruit_name', 'apple').update({
          amount: '5'    //just for this post
        })
          .then(res.sendStatus(200))
          .catch(res.sendStatus(500))
      }
    })
    .catch(error => {
      res.sendStatus(500)
    })

I don't understand why the catch block is being executed and the server gave me the Can't set header after sending them error. This error occur because I am sending two res.sendStatus. The .then block are working fine and .catch block should not be executed unless the data fails to store in DB.

This is written in knex.js in a Node Express server and for just in case, the query statement is querying the fruit table where fruit_name column's item is equals to apple, insert new amount row if apple doesn't exist else if exist update the amount row.


Solution

  • db('fruit').where('fruit_name', 'apple')
    .then(data => {
      if (data.length === 0) {
        db('fruit').insert({
          amount: '2'     //just for this post
        })
          .then(()=>res.sendStatus(200))
          .catch(()=>res.sendStatus(500));
      }
      else {
        db('fruit').where('fruit_name', 'apple').update({
          amount: '5'    //just for this post
        })
          .then(()=>res.sendStatus(200))
          .catch(()=>res.sendStatus(500))
      }
    })
    .catch(error => {
     return res.sendStatus(500)
    })
    

    Hi calvert. You need to return your responses.This should work fine now.