【发布时间】:2021-05-25 20:47:47
【问题描述】:
我是续集和尝试减量的新手。我有两种型号的产品和订单,在产品中有 productStock 列,在 order 中有数量列。我想要做的是当我创建新订单时 productStock 将减少取决于订购的数量。代码如下:
router.post('/', async (req, res) => {
try {
const { productId, quantity } = req.body
const postData = new Order({
productId,
quantity
})
const resultdata = await Product.findOne({ where: {productId: postData.productId} }).then( product => {
if(product.productStock <= 0) {
return res.json({
status: "failed",
message: "out of stock"
})
} else {
product.decrement('productStock', {by: postData.quantity})
return postData.save()
}
} ).catch(err => err)
res.send({
status: "success",
data: resultdata
})
} catch (err) {
throw err
}
})
我得到了我想要的结果,但问题是当 productStock
(node:13236) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Socket'
| property '_writableState' -> object with constructor 'WritableState'
| property 'afterWriteTickInfo' -> object with constructor 'Object'
--- property 'stream' closes the circle
at JSON.stringify (<anonymous>)
at stringify (D:\Projects\sequelize-association\node_modules\express\lib\response.js:1123:12)
at ServerResponse.json (D:\Projects\sequelize-association\node_modules\express\lib\response.js:260:14)
at ServerResponse.send (D:\Projects\sequelize-association\node_modules\express\lib\response.js:158:21)
at D:\Projects\sequelize-association\routes\orders.js:30:13
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:13236) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated
either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13236) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
请任何人帮忙,我认为我的代码不干净,因为在 try/catch 中使用了 then/catch
【问题讨论】:
标签: node.js sequelize.js mysql2 node-mysql decrement