NodeJs+express+mongoDB接口中,在循环中写`res.json`时会报错(Cannot set headers after they are sent to the client)
var isShow = false; //定义开关变量
//loadcurr为数组,具体内容省略了
loadcurr.forEach(item => {Stock.findOneAndUpdate({ //Stock是用来连接数据库集合的_id: ObjectId(item._id)}, {$set: {//此处省略要修改的内容。。。。。。}},function (err, data) {if (err) {console.log(err)} else {//此处应该写res.json,但是为了解决报错让前面定义的变量为trueisShow = trueconsole.log('1', isShow);}})
})
console.log('2', isShow);
if (isShow == true) {res.json({status: "200"})
}
这样就可以成功解决Cannot set headers after they are sent to the client的错啦!!!
注意:
如果上面的代码执行顺序是先打印了console.log('2', isShow);后打印console.log('1', isShow);,说明存在异步,因此用异步解决即可,具体实现如下所示(若顺序是先执行console.log('1', isShow);后执行console.log('2', isShow);就是正确的):
var isShow = false;(async function(){await new Promise((resolve, reject) => {//loadcurr为数组,具体内容省略了loadcurr.forEach(item => {//Stock是用来连接数据库集合的Stock.findOneAndUpdate({_id: ObjectId(item._id)}, {$set: {//此处省略要修改的内容。。。。。。}},function (err, data) {if (err) {console.log(err)} else {resolve(isShow = true)console.log('1', isShow);}})})})console.log('2', isShow);if (isShow == true) {res.json({status: "200"})}})()
var isShow = false;(async function(){//loadcurr为数组,具体内容省略了await loadcurr.forEach(item => {//Stock是用来连接数据库集合的_id: ObjectId(item._id)}, {$set: {//此处省略要修改的内容。。。。。。}},function (err, data) {if (err) {console.log(err)} else {isShow = trueconsole.log('1', isShow);}})})console.log('2', isShow);if (isShow == true) {res.json({status: "200"})}})()
好啦,以上就是解决循环里面写res.json报错问题及解决异步问题!在这两个问题没少费工夫??????
有问题欢迎指出,若有更好的解决方案欢迎在下面??????分享哦!!!
本文发布于:2024-02-02 10:35:34,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170684133343233.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |