.then操作成功时执行捕获

时间:2019-01-24 17:39:08

标签: node.js callback response knex.js

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)
    })

我不明白为什么执行catch块并且服务器给了我Can't set header after sending them错误。发生此错误,因为我正在发送两个res.sendStatus。 .then块工作正常,除非数据无法存储在DB中,否则不应执行.catch块。

这是用Node Express服务器中的knex.js编写的,为了以防万一,查询语句正在查询Fruit表,其中fruit_name列的项目等于apple,如果apple不存在,则插入新的金额行,否则存在更新金额行。

1 个答案:

答案 0 :(得分:1)

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)
})

您好,卡尔弗特。您需要返回您的回复。现在应该可以了。

相关问题