首页 > 解决方案 > mongoDb 中的 API 响应发送问题。

问题描述

我正在使用 mongodb 制作后端 API。我曾经使用bluebird过承诺。

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 时,我怎么能停止下一次执行。

我已经将资源发送给客户端,然后它也执行下一个代码,在其他部分我还发送了成功/错误资源。这就是我收到此错误的原因。

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

我曾尝试使用return, return false。但它仍然在执行我的下一个代码。

标签: javascriptmongodbpromiseresponse

解决方案


不需要在您的 return 语句中创建新的 Promise,如果您需要您的方法来生成 Promise,您可以返回链本身。
thenin promise 链返回并不会停止链,它只是将返回的值作为参数传递给 next 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.collection("employee").insert({...})返回的任何内容。


推荐阅读