【发布时间】:2021-04-19 16:49:43
【问题描述】:
目前正处于职业过渡期,我正在从事一个研究项目,我必须在其中创建一种迷你论坛。我为我的数据库使用了 node.js/express 和 sequelize。 在下面的代码中,我的 API 尝试检索最后 10 条消息(带有分页内容)发送到我的欢迎页面。它完美地工作。问题是某些消息的标题为空,因为它们只是其他消息的答案。我想用我保存到数据库中的 parent_id_msg 标题来更改这个空标题。
但是由于异步代码,我收到了 Promise 对象,但我无法将它用于我的同步代码(导致最后未定义的标题)。在阅读了许多资源并尝试了过去 3 天的一些解决方案之后,我想我理解了与同步代码一起使用的 async/await 的问题,但我仍然不明白如何覆盖它并取得进展。
PS:我不确定我的“异步列表”,但我不知道将异步放在哪里:(
exports.lastsMessages = (req, res, next) => {
//find 10 last messages (responses includes)
let answer = {
count : 0,
list:[]
};
let tmp;
Message.findAndCountAll({
order:[['creation_date', 'DESC']],
offset: 10 * req.body.pageNbr - 10,
limit: 10
})
.then( async list=>{
answer.count = list.count;
for(let i = 0; i<list.rows.length;i++){
tmp = list.rows[i].dataValues;
if(tmp.title === null || tmp.title === ""){
console.log('before'+ tmp.title) // output NULL as expected
tmp.title = await findTitle(tmp.parent_msg_id);
console.log('after '+ tmp.title)// output undefined, not as expected :(
}
answer.list.push(tmp)
};
res.status(200).json({...answer, message:'10 derniers messages'})
})
.catch(error => res.status(400).json({error, message:'Messages non récupérés'}));
};
async function findTitle(parentId){
Message.findOne(
{attributes:['title'],
where:{id:parentId}})
.then(potatoes=> {
console.log('inside '+ potatoes.dataValues.title)
//output parent message title inside function, as excepted
return potatoes.dataValues.title});
};
提前感谢您(对于潜在的错误、误解和英语水平,作为初学者,我们深表歉意)
【问题讨论】:
标签: node.js asynchronous async-await