使用ES6 Promise,如何在以下情况下将其分解?NodeJS违反Promise
addClient: function(request, response, next) {
var id = mongo.validateString(request.body.id);
mongo.Test.findOne({
id: id
})
.then(client => {
if (client) {
// want to break here
response.status(400).send({
error: 'client already exists'
});
} else {
return auth.hashPassword(mongo.validateString(request.body.secret));
}
})
.then(hashedSecret => {
// gets executed even if I don't return anything
return new mongo.Test({
name: mongo.validateString(request.body.name),
id: id,
secret: hashedSecret
}).save();
})
.then(doc => {
return response.status(201).send({
client: {
id: doc._id
}
});
})
.catch(err => {
return next(err);
});
}
我还没有找到任何明确的文档说明如何打破这一点。 而不是链接then
我可以在第一个then
内部,但在更复杂的请求,它将是很高兴能够让他们链接。
我不确定这是干净的,规范的方式可能。看到[这个答案](https://stackoverflow.com/questions/29478751/how-to-cancel-an-emcascript6-vanilla-javascript-promise-chain)为类似的东西。过去,我通过每个'then'返回'null'来实现这一点,这是令人恐怖的混乱;或者当我想在'catch'语句中打破并测试这个语句时抛出,这又一次让人觉得很尴尬。 –