node.js - save() 被调用一次,但在猫鼬中第一次被执行两次
问题描述
我正在创建一个待办事项列表,该列表在 url 上更改参数时动态创建一个列表。如果该列表已经存在,它会呈现该列表并且不会再次创建。但是,当我运行代码并给它一个随机路由时,它基本上执行 list.save() 两次,但只是第一次。从第二次开始,它运行正常。怎么了?
app.get("/:customListName", function (req, res) {
const customListName = req.params.customListName;
List.findOne({ name: customListName }, function (err, foundList) {
if (!err) {
if (!foundList) {
const list = new List({
name: customListName,
items: defaultItems
})
list.save();
res.redirect("/" + customListName);
} else {
res.render('list', { aajakoDay: foundList.name, listItems: foundList.items })
}
}
})
})
解决方案
我认为重定向是导致问题的原因
res.redirect("/" + customListName);
list.save() 本身似乎是异步函数。因此,您在实际保存之前重定向它。现在,当它被重定向时,它仍然没有找到(尚未保存到 DB)并且 save() 再次执行。
如果可能的话(传递另一个回调函数),将响应部分移动到 save() 函数中,或者使用 await 等待其保存,然后进行重定向。
另一种方法是重定向到“/”或主页。
您还可以使用 async-await 功能来解决 Promise 并使代码更加干净和高效。
app.get("/:customListName",async function(req,res){
try{
const customListName = req.params.customListName;
let listItem = await List.findOne({ name: customListName });
//if listitem is found in db
if(listItem){
return res.render('list',{ aajakoDay: foundList.name,
listItems: foundList.items })
}
else{
//create the listItem
let newListItem = await List.create({name:customListName, items:defaultItems});
await newListItem.save();
return res.redirect("/" + customListName);
}
}catch(err){
console.log("Error: ",err);
return;
}
});
你可以参考这篇博客:https ://blog.risingstack.com/mastering-async-await-in-nodejs/
推荐阅读
- scala - 如何从scala spark中的并行列表构造(键,值)列表?
- asp.net-mvc - Adobe 嵌入的 PDF 保存到服务器提供损坏的文件
- reactjs - 在带有特征和图层的 react-mapbox-gl 中显示标记
- node.js - 一个文件中的 Json 值,基于另一个 Json 文件中的字段
- python - pyqtgraph ErrorBarItem 不绘制连接水平误差线的垂直线
- c# - 从 .NET Core 3.1 中的 AWS Lambda 函数将字节上传到 SFTP 服务器
- c# - C# 协程在 Unity 中不起作用
- java - 如何将 2 个内部类相互映射
- android - 当我运行我的颤振应用程序时,只显示空白屏幕
- c# - C# WPF 从墨水画布渲染真正的单色图像