ES6 약속을 사용하면 다음 시나리오에서 어떻게 해결할 수 있습니까?NodeJS가 약속을 깨기
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"문에서 중단하고 테스트하려고 할 때 던지는 것입니다.이 문장은 다시 해커라고 느껴집니다. –