javascript - 查询结果循环中的nodejs查询
问题描述
我正在使用 nodejs/mysql 执行 mysql 查询。
在第一个结果集之后,我将遍历结果集并查询第二个表。
1)为什么'for'有效而'foreach'无效?实现我需要的正确循环方式是什么?
2) getImage 函数中的 item = { ...item, images: rows } 也不起作用,为什么?
3)如何让console.log显示修改后的结果?如果我使用'await',console.log(rows) 应该显示修改后的结果对吗?
const getImages = async (item, key) => {
let sql = await connection.format('SELECT * from `images` WHERE id = ?', [item.id]);
const [ rows , fields ] = await connection.execute(sql);
item['images'] = rows
item = { ...item, images: rows } //'<-- this method doesn't work.
return item
}
let sql = await connection.format(`SELECT * from table ORDER BY a.listing_id LIMIT ?,?`, [0,10])
var [rows, fields] = await connection.execute(sql);
// rows.forEach(getImages) //'<-- this does not work when uncommented
// rows = rows.forEach(getImages) //'<-- this also does not work when uncommented.
for (let i = 0; i < rows.length; i++) { //'<-- but this works
rows[i] = await getImages(rows[i], i);
}
console.log(rows) //<----- this doesn't show modified results on terminal console
res.json(rows) //<----- browser can see the modified results on browser console
解决方案
您必须将每个项目的正确处理程序传递给 foreach 方法:
let new_rows = Array()
rows.forEach(row => {
new_rows.push(await getImages(row, i))
});
另外,如果你想在另一个数组上获取图像,你应该使用 map,它更干净:
let new_rows = rows.map(row => {
return await getImages(row, i)
});
推荐阅读
- apache-spark - 在 Pyspark 中使用结构化流读取数据并希望写入文件大小为 100MB 的数据
- bash - 如何使用 unzip 命令解压缩文件?
- python-3.x - 为什么我的代码 python 只能将文件 .CSV 中的一些数据导入我的数据库 PostgreSQL?
- php - 按键从json文件中删除一个项目
- python-3.x - 得到 UnimplementedError:不支持将字符串转换为浮点数
- microsoft-graph-api - 需要升级 Microsoft graph 帐户才能创建可共享链接
- r - R中的递归函数,终点因组而异
- php - 我该怎么做我想将视图存储在 1000=1k、100000=100k、1000000=1M 等
- spring - 立即使用 Rest API 响应空文件下载 zip 文件
- html - 当我按下按钮时背景图像移动