我承诺在express上使用mysql2从mysql数据库中获取数据。我需要在运行另一个查询后将第一个查询中的数据获取到最终返回的对象中。
db.query("SELECT * FROM users_tasks_link WHERE uin = ?", [req.params.id])
.then(result => {
const foo = db.query(
"SELECT * FROM tasks WHERE id IN (?); SELECT * FROM headers; SELECT * FROM categories; SELECT * FROM links",
[
result[0].map(e => {
return e.task_id;
})
]
);
return foo;
})
.then(foo => {
let tasks = [];
foo[0][0].forEach(element => {
let task = {
id: element.id,
title: element.title,
header: foo[0][1].filter(e => element.header === e.id)[0].header,
category: foo[0][2].filter(e => element.category === e.id)[0].category,
notes: element.notes,
level: element.level,
links: foo[0][3]
.filter(e => element.id === e.task_id)
.map(el => {
return {
name: el.name,
link: el.link
};
})
};
tasks.push(task);
});
return res.send({ data: tasks, message: "Got all tasks for user" });
})
.catch(err => {
console.log(err);
});
我需要任务对象中"结果"的值,但我无法访问"foo"的结果数据。
在调用 db.query 之前创建一个范围更高的变量。并将结果存储在其中以供以后引用:
var datavar;
db.query("SELECT * FROM users_tasks_link WHERE uin = ?", [req.params.id])
.then(result => {
datavar = result;
const foo = db.query(
"SELECT * FROM tasks WHERE id IN (?); SELECT * FROM headers; SELECT * FROM categories; SELECT * FROM links",
[
result[0].map(e => {
return e.task_id;
})
]
);
return foo;
}).then(foo => { // You can now use datavar to access the data you want }