【发布时间】:2019-01-27 05:27:28
【问题描述】:
所以我有一个 Express 应用程序,它使用中间件解析 JSON POST 请求,然后填充 req.body 对象。然后我有一个承诺链,它使用 Joi 根据模式验证数据,然后将其存储在数据库中。
我想要做的是检查在这些过程之一之后是否引发了错误,通过发送状态代码适当地处理它,然后完全中止承诺链。我觉得应该有一些非常干净和简单的方法来做到这一点,(也许是某种中断声明?)但我在任何地方都找不到。这是我的代码。我让 cmets 显示了我希望中止承诺链的位置。
const joi = require("joi");
const createUserSchema = joi.object().keys({
username: joi.string().alphanum().min(4).max(30).required(),
password: joi.string().alphanum().min(2).max(30).required(),
});
//Here begins my promise chain
app.post("/createUser", (req, res) => {
//validate javascript object against the createUserSchema before storing in database
createUserSchema.validate(req.body)
.catch(validationError => {
res.sendStatus(400);
//CLEANLY ABORT the promise chain here
})
.then(validatedUser => {
//accepts a hash of inputs and stores it in a database
return createUser({
username: validatedUser.username,
password: validatedUser.password
})
.catch(error => {
res.sendStatus(500);
//CLEANLY ABORT the promise chain here
})
//Only now, if both promises are resolved do I send status 200
.then(() => {
res.sendStatus(200);
}
)
});
【问题讨论】:
标签: javascript node.js express promise