javascript - 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
。但它仍然在执行我的下一个代码。
解决方案
不需要在您的 return 语句中创建新的 Promise,如果您需要您的方法来生成 Promise,您可以返回链本身。
从then
in 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({...})
返回的任何内容。
推荐阅读
- python - 使用带有 TimeDistributed LSTM 层的 CNN 编码器来解决拼图问题
- html - 无法从滚动中冻结带有 CSS 的两个第一列
- python - 从未知多项式函数中找到系数的最优解
- css - Safari 切断虚线边框的第一个和最后一个破折号
- elasticsearch - 如何在两个单独的服务器之间使用 Logstash 将日志从文件发送到 Elasticsearch?
- r - 将复杂数据从一个 Dataframe 获取到另一个 Dataframe
- java - Java,硒超时异常
- vb.net - 表单在 vb.net 中加载缓慢
- javascript - Ajax 不发出警报就无法工作
- c# - Selenium 在模拟器中间歇性点击