首页 > 解决方案 > .then操作成功时执行catch

问题描述

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_name 列的项目等于 apple 的水果表,如果 apple 不存在则插入新的金额行,否则如果存在则更新金额行。

标签: node.jscallbackresponseknex.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 => {
 return res.sendStatus(500)
})

嗨卡尔弗特。您需要返回您的回复。现在应该可以正常工作了。


推荐阅读