How to break the promise chain during database insertion if the data already exists in the database?
P粉725827686
P粉725827686 2023-08-17 23:08:43
0
1
372

I'm using mongoose to create a new member entry in the database after checking if the member already exists in the database. I need to return a response if the member already exists, otherwise continue inserting the new member. Here is the code:

createNewMember = (req, res, next) => { Member.findOne({email: email}).exec() .then((members) => { if(members == null || members.length==0) { //Create new member object return newMember.save() // 1 --> return promise } else { res.status(409).json({message: "Member already exists"}) // 2 --> I want to return } }) .then((result) => { if(res.statusCode === 409) return res; // 3 --> I added this hack to solve the problem return res.status(201).json({message: "Member has been created"}); // 4 --> then block of newMember.save() }) .catch(err => { // Handle the error and return an error response })

What I want is that if the process reaches point 2, the promise chain is broken, but the second then block is still called. Point 3 is a check I added to prevent the second then block from being executed, but I don't think this is the best way to handle it. I believe this is a common scenario, is there a better way?

P粉725827686
P粉725827686

reply all (1)
P粉316110779

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 => { // 处理错误并返回错误响应 })
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!