node.js - .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 不存在则插入新的金额行,否则如果存在则更新金额行。
解决方案
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)
})
嗨卡尔弗特。您需要返回您的回复。现在应该可以正常工作了。
推荐阅读
- tensorflow - Tensorflow2 Adabound 实现中非槽变量的无类型
- regex - Go Negative LookAhead 替代方案
- javascript - 错误 TS2739:类型“{}”缺少类型中的以下属性
- jenkins - 詹金斯错误:标签必须遵循要求的规范
- javascript - 谷歌图表 - 晚上 8 点到早上 6 点(xAxis) - 工作日
- c# - 如何区分用户退出聊天和处于睡眠模式的客户端?
- c# - .Net - 访问方法“Amazon.SimpleNotificationService.Model.ListTopicsRequest”失败
- ruby-on-rails - Rails 6:我可以为 Webpacker 文件添加资产前缀吗?
- ruby-on-rails - 由于将 rails 从 3 迁移到 5,升级配置更少
- bash - 关闭执行命令的返回消息