P粉3161107792023-08-18 21:15:35
There is no way to break the promise chain except throwing your own error and jumping to the catch block. However, you don't want to use an error like that, because the situation itself is not an error, but just a specific logical situation (the member already exists). I recommend thinking of your .then() as layers of cake with different concerns, like this:
Member.findOne({email: email}).exec() // DB layer .then((members) => { // 如果成员不存在,则开始保存并返回promise if(members == null || members.length==0) { // 创建newMember对象 return newMember.save() // 1 --> 返回promise } // 如果成员存在,则返回undefined else { return; } }) // Response Layer .then((newMember) => { let statusCode; let message; // 在.save()成功时,promise解析为新成员 if(newMember) { statusCode = 201; message = "成员已创建"; } // 如果我们在第一个.then()中返回了undefined,我们会到达这里 else { statusCode = 409; message = "成员已存在"; } return res.status(statusCode).json({message}); }) .catch(err => { // 处理错误并返回错误响应 })