目前正处于职业转型期,我正在开展一个学习项目,我必须在其中创建一种小型论坛。我为我的数据库使用了 node.js/express 和 sequelize。 在下面的代码中,我的 API 尝试检索最后 10 条消息(带有分页内容)以发送到我的欢迎页面。它完美地工作。问题是有些消息的标题为空,因为它们只是其他消息的答案。我想通过我保存到 db 中的 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});
};
在此先感谢您(对于潜在的错误、误解和英语水平,对于初学者很抱歉)
答案 0 :(得分:0)
您没有从 findTitle 返回任何内容。
在 findTitle 函数的第一行试试这个:
return Message.findOne(...
此外, findTitle 函数不需要是异步的,因为您没有在其中使用 await。另一方面,在循环内使用 await 通常是一个坏主意。