数据库查询function query(sql) { return new promise((resolve, reject) => { pool.getConnection(function (err, conn) { if (err) { reject(err); } else { conn.query(sql, function (err, rows, cols) { if (err) { conn.release(); reject(err) } else { //释放连接 conn.release(); //事件驱动回调 resolve({ rows: rows, cols: cols }); } }); } }); });};exports.myTickets = (userId, cb) => { let sql = util.format('select ticketId,number from ticket_Numbers where userId="%s"', userId); db.query(sql) .then((data) => { let tickets = data.rows; tickets.map(ticket => { db.query(util.format('select userId,number from ticket_numbers where ticketId="%s"', ticket.ticketId)) .then((players) => { ticket.players = players.rows; }); }) console.log(tickets); //这里log出来有players console.log(JSON.stringify(tickets)); //stringify之后 players丢失 cb({ success: true, tickets: tickets }); }) .catch(err => { console.log(err.stack); cb({ success: false, message: err.message }); });}结果:node新手,请教为什么会这样,哪里写错了?
1 回答
浮云间
TA贡献1829条经验 获得超4个赞
let getTickets = (userId) => {
let sql = util.format('select ticketId,number from ticket_Numbers where userId="%s"', userId);
return db.query(sql);
}
exports.myTickets = function (userId, cb) {
getTickets(userId).then(async (data) => {
let tickets = data.rows;
for (let ticket of tickets) {
await db.query(util.format('select userId,number from ticket_numbers where ticketId="%s"', ticket.ticketId))
.then((players) => {
ticket.players = players.rows
});
}
cb({ success: true, tickets: tickets });
});
}
搞定了
添加回答
举报
0/150
提交
取消