express - 使用 express 和 sequelize with promise 调用用户的评论和回复
问题描述
我是表达和续集的新手。我正在尝试使用 Express 路由器的 Promise 回复用户的评论,但它不起作用,请指导我解决问题。
首先,我用于var loopIndex = 0
检查用户注册的帖子长度。它工作正常。
1.路由器零件
router.get('/show', function(req, res){
models.post.findAll({
order: [["createdAt", "DESC"]]
})
.then(function(result){
var loopIndex = 0
for(let post of result){
models.post.find({
include: {model: models.reply, where: {postId: post.id}}
})
.then(function(result2){
if(result2){
post.replies = result2.replies
}
loopIndex++
if(loopIndex === result.length){
res.render('show', {
posts: result
})
}
})
}
})
.catch(function(err){
console.log(err)
})})
2.ejs文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>Add comments</h1> <hr>
<form action="/create" method="POST">
<table style="margin-bottom:50px;">
<tr>
<td>
<input type="text" name="inputTitle" placeholder="Title.">
</td>
</tr>
<tr>
<td>
<input type="text" name="inputWriter" placeholder="Author.">
</td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</table>
</form>
<% for(let post of posts) { %>
<table style="border: solid black 1px; margin-bottom:30px;">
<tr>
<td>Title</td>
<td>Author</td>
<td>Date</td>
</tr>
<tr>
<td><%= post.title %></td>
<td><%= post.writer %></td>
<td><%= post.createdAt %></td>
<td><button ><a href="/edit/<%=post.id%>">Edit</a></button></td>
<td><button ><a href="/delete/<%=post.id%>">Delete</a></button></td>
</tr>
<tr>
<td><hr></td>
</tr>
<form action="/reply/<%=post.id%>" method="post">
<tr>
<td><input type="text" name="replyWriter" placeholder="Author"></td>
<td><input type="text" name="replyContent" placeholder="Description"></td>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
</tr>
</form>
</table>
<% if(post.replies){for(let reply of post.replies)
{ %>
<tr>
<td><%= reply.dataValues.writer %></td>
<td><%= reply.dataValues.content %></td>
</tr>
<% } %>
<% } %>
<% } %>
</body>
</html>
我尝试使用 Promise 编写代码。但它不起作用。
3.使用promise修改代码
var post_reply = new Promise(function(result){
models.post.findAll({
order: [["createdAt", "DESC"]]
})
.then(function(result){
for(let post of result){
models.post.find({
include: {model: models.reply, where: {postId: post.id}}
})
.then(function(result2){
if(result2){
post.replies = result2.replies
}
})
}
})
return result
})
router.get('/show', function(res, req){
post_reply.then(function(result){
res.render('show', {
posts: result
})
}).catch(function(err) {
console.log(err)
})
})
循环或嵌套函数有问题吗?
解决方案
推荐阅读
- html - 如何使用适当的样式连接 Django 应用程序和 HTML 模板?
- javascript - Jquery 启用/禁用按钮 textarea 验证
- python - 如何访问字典中的字典键?
- python - 将 colab 用于 python ADT 的
- c++ - 如何使用堆栈将输入的字符串拉伸 k 次
- css - 在 flexbox 中,为什么我的按钮似乎被压缩了?
- android - Android 工作人员被取消,没有显示原因
- node.js - 编辑路由 index.js 文件后,Vue js 路由不会更新
- if-statement - NFC If 语句 C++
- python - 如何使嵌入矩阵的一部分可训练,而其余部分在 pytorch 中不可训练?