Javascript mongoDb中的API响应发送问题。

Javascript mongoDb中的API响应发送问题。,javascript,mongodb,promise,response,Javascript,Mongodb,Promise,Response,我正在使用mongodb制作后端API。我用蓝鸟来表达我的承诺 return new promise((resolve, reject) => { db.collection('employee').find({ email: data.email }).toArray().then((checkEmail) => { if (checkEmail.length > 0) {

我正在使用mongodb制作后端API。我用蓝鸟来表达我的承诺

return new promise((resolve, reject) => {

    db.collection('employee').find({
        email: data.email
    }).toArray().then((checkEmail) => {
        if (checkEmail.length > 0) {                
            res.send({ status: 0, message: 'Employee already exist.' });
            // I want to stop my node hear. 
            // I have tried return false , but not works.
        }
    }).then(() => {
        // Add employee details into collection as a new employee. 
        return db.collection('employee').insert({
            //...
        })
    }).then((employee) => {
         // Other stuff
    }).catch((error) => {
        console.log(error)
        res.send({ status: 0, message: 'Something went wrong.' });
    });;
}
正如你们所看到的,若checkEmail>0,那个么我已经发送了我在邮递员那个里得到的正确回复。但我的节点仍然是执行下一个代码

那么,当我发送res返回时,如何停止下一次执行呢

我已经将res发送到客户端,然后它执行下一个代码,在其他部分,我也发送了success/error res。这就是为什么我会出现这个错误

Error: Can't set headers after they are sent.

我试着用return,returnfalse。但它仍然需要执行我的下一个代码

不需要在返回语句中创建新承诺,如果需要方法生成承诺,可以返回链本身。 从承诺链中的then返回不会停止该链,它只是将返回的值作为参数传递给下一个then。绕过它的一种方法是抛出您自己的自定义错误,并在catch中适当地处理它。像这样的方法应该会奏效:

return db
  .collection("employee")
  .find({email: data.email})
  .toArray()
  .then(checkEmail => {
    if (checkEmail.length > 0) {
      let err = new Error("Employee already exists.");
      err.code = "EMPLOYEE_ALREADY_EXISTS";
      throw err;
    }
  })
  .then(() => {
    // Add employee details into collection as a new employee.
    return db.collection("employee").insert({
      //...
    });
  })
  .then(employee => {
    // Other stuff
  })
  .catch(error => {
    if (error.code && error.code === "EMPLOYEE_ALREADY_EXISTS") {
      res.send({ status: 0, message: "Employee already exists." });
    } else {
      console.log(error);
      res.send({ status: 0, message: "Something went wrong." });
    }
  });

编辑:再次明确,第三个then中的员工将是您从上一个then返回的任何内容,即db.collectionemployee.insert{…}返回的任何内容。

您可以像

db.collection('employee')
.find({
    email: data.email
 })
.toArray()
.then((checkEmail) => {
   if (checkEmail.length > 0) {                
     return res.send({ status: 0, message: 'Employee already exist.'});
   }
   else
   {
     return db.collection('employee').insert({
        //...
        })
        .then((employee) => {
           // Other stuff})
        })
   }
})
.catch((error) => {
    console.log(error)
    res.send({ status: 0, message: 'Something went wrong.' });
});
或者你可以通过绑定不同的onSuccess调用来分支你的承诺。 一个分支将决定是否发送消息。由于承诺是链接的,所以唯一的方法是像在另一个分支中一样在整个承诺链中传递状态

let exists = db.collection('employee')
    .find({
        email: data.email
     })
    .toArray()

 exists.then((checkEmail)=>{
    if(checkEmail.length > 0){
       return res.send({ status: 0, message: 'Employee already exist.'});
       //ends the excution here
    }
 })
 exists.then((checkEmail)=>{
      return checkEmail.length === 0;
   }
 })
 .then((createUser) => {
   if(createUser){
     return db.collection('employee').insert({
        //...
    })
    else
     return createUser
   }
 })
 .then((createUser)=> {
   if(createUser) {
     // Other stuff
   }
 })
 .catch((err)=>{
    console.log(error)
    res.send({ status: 0, message: 'Something went wrong.' });
 })

从then返回不会停止承诺链,而是将返回的值传递给链中的下一个then。您可以抛出自己的错误,并在捕获中以与处理一般错误不同的方式处理它。e:我还建议用Promise和javascript来标记这个问题,因为它与mongodb并不完全相关。嵌套承诺而不是将它们链接起来难道不被认为是一种反模式吗?这在用例上是主观的,但如果它被过度使用,那么是一种糟糕的做法。让我编辑我的solution@V谢谢你的回复。我已尝试返回res.send{状态:0,消息:“员工已存在”。};但这对我不起作用。