nodejs 表达嵌套续集异步等待
nodejs express nested sequelize async await
我无法使嵌套逻辑起作用。我需要将来自 2 table 和 return 的数据合并到请求中。我不想加入 table,因为我需要 return 来自 tableA 的单个记录,然后在 returned 之前与 tableB 记录结合.下面是我的简化代码
exports.get_caution_reasons = async (req, res) => {
let return_data = [];
await db.sequelize.query("SELECT TableA xxxxx",{
type: QueryTypes.SELECT
}).then(recordA => {
for (let index = 0; index < recordA.length; index++) {
return_data.push({recordA[index].xxx, recordA[index].yyy})
db.sequelize.query("SELECT TableB xxxxx WHERE zzz=recordA.zzz",{
type: QueryTypes.SELECT
}).then(recordB => {
for (let index = 0; index < recordB.length; index++) {
return_data.push({recordB[index].xxx, recordB[index].yyy})
}
})
}
res.status(200).json({data: return_data});
})
};
它只是 return 表 A 的记录而已。我尝试了各种异步并等待将 recordB 放入其中但没有成功。任何帮助都是有用的。
可能类似的东西应该有效:
exports.get_caution_reasons = async (req, res, next) => {
try {
let options = { type: QueryTypes.SELECT }
let data = []
let result_a = await db.sequelize.query("SELECT TableA xxxxx", options)
for (let index = 0; index < result_a.length; index++) {
data.push({ /* whatever you need... */ })
let result_b = await db.sequelize.query("SELECT TableB xxxxx WHERE zzz=recordA.zzz", options)
for (let index = 0; index < result_b.length; index++) {
data.push({ /* ... */ })
}
}
res.json({ data })
} catch (err) {
next(err)
}
}
我无法使嵌套逻辑起作用。我需要将来自 2 table 和 return 的数据合并到请求中。我不想加入 table,因为我需要 return 来自 tableA 的单个记录,然后在 returned 之前与 tableB 记录结合.下面是我的简化代码
exports.get_caution_reasons = async (req, res) => {
let return_data = [];
await db.sequelize.query("SELECT TableA xxxxx",{
type: QueryTypes.SELECT
}).then(recordA => {
for (let index = 0; index < recordA.length; index++) {
return_data.push({recordA[index].xxx, recordA[index].yyy})
db.sequelize.query("SELECT TableB xxxxx WHERE zzz=recordA.zzz",{
type: QueryTypes.SELECT
}).then(recordB => {
for (let index = 0; index < recordB.length; index++) {
return_data.push({recordB[index].xxx, recordB[index].yyy})
}
})
}
res.status(200).json({data: return_data});
})
};
它只是 return 表 A 的记录而已。我尝试了各种异步并等待将 recordB 放入其中但没有成功。任何帮助都是有用的。
可能类似的东西应该有效:
exports.get_caution_reasons = async (req, res, next) => {
try {
let options = { type: QueryTypes.SELECT }
let data = []
let result_a = await db.sequelize.query("SELECT TableA xxxxx", options)
for (let index = 0; index < result_a.length; index++) {
data.push({ /* whatever you need... */ })
let result_b = await db.sequelize.query("SELECT TableB xxxxx WHERE zzz=recordA.zzz", options)
for (let index = 0; index < result_b.length; index++) {
data.push({ /* ... */ })
}
}
res.json({ data })
} catch (err) {
next(err)
}
}