Javascript NodeJS+;MySql嵌套查询
我试图从数据库中获取用户,然后循环遍历每个用户并获取他们的图像。但是,当我尝试将images数组分配给user.images属性时,什么也没有发生。我仍然只得到具有空图像数组的用户 目前我的代码如下:Javascript NodeJS+;MySql嵌套查询,javascript,mysql,node.js,Javascript,Mysql,Node.js,我试图从数据库中获取用户,然后循环遍历每个用户并获取他们的图像。但是,当我尝试将images数组分配给user.images属性时,什么也没有发生。我仍然只得到具有空图像数组的用户 目前我的代码如下: user.getAll().then(result =>{ const userCollection = result[0]; for(let i=0; i < userCollection.length; i++){ userCollection[i
user.getAll().then(result =>{
const userCollection = result[0];
for(let i=0; i < userCollection.length; i++){
userCollection[i].images = [{}];
image.getImagesByUserId(userCollection[i].Id).then(res =>{
userCollection[i].images = res[0];
}).catch(err =>{
console.log(err);
res.status(400).json(err);
})
}
res.json(userCollection);
})
.catch(err =>{
console.log(err);
res.status(400).json(err);
});
user.getAll()。然后(结果=>{
const userCollection=结果[0];
for(设i=0;i{
userCollection[i].images=res[0];
}).catch(错误=>{
控制台日志(err);
res.status(400).json(err);
})
}
res.json(userCollection);
})
.catch(错误=>{
控制台日志(err);
res.status(400).json(err);
});
为什么我不能将images数组分配给它的属性?可能是个愚蠢的问题,但您是否分配了它?我只看到 userCollection[i]。图像=[{}] 在上面,永远看不到: userCollection[i].images=res
一旦你抓到了图片,你就可以分配任务了 在我看来,您需要从回调内部运行res.json(userCollection) 这当然意味着您需要在回调中重命名res变量
这是假设您以某种方式使用res.json(userCollection)导出信息。我是基于这样一个事实推断的,我没有看到res在任何地方定义,问题是
getImagesBySerid()
是异步的,所以当您到达分配时,您已经发送了响应
您当前拥有的事件顺序为:
res.json()
)SELECT image_name, user_id
FROM image
然后将js中的循环替换为:
getImagesForUsers().then(result => {
//create your response from the rows
res.json(response);
});
接得好-但我在分配,只是错过了这里。我只是编辑了我的代码,只是为了弄清楚-当我console.log res[0]时-我看到了我的图像,但当我尝试分配它时-它保持为空属性我尝试了几个带有Promise.all()的选项,但我对JS和node非常陌生,所以我找不到好的示例。关于单次查询-您的意思是最好从数据库中获取通用数组用户+图像,并尝试将它们插入到.then语句中?是的,最好一次从数据库中获取所需的所有数据,而不是进行大量的小查询。另一个帮助您的方法是使用async Wait关键字,而不是使用then。请参阅“创建承诺数组”是一个与你的承诺类似的例子。all()感谢你的评论。这是完整调用的外观:router.get('/',(req,res)=>{…问题代码});你能建议把res.json(userCollection)放在哪里吗?要使它正常工作,应该直接在userCollection下面[i] .images=res[0]