如何让这个变量在我获取数据后执行?
How to make this variable execture after i get the data?
我不知道问题出在哪里,我知道标题没有描述任何我对此表示歉意的内容。
这是我面临的问题。
我目前在 MERN 应用程序中工作。
我在 express 中有一条路线,我从两个表中请求数据库中的一些数据。
playlist.post("/getplaylistSongs", (req, res) => {
const { cookie } = req.body;
const sql = "SELECT * FROM playlist WHERE user_id = ?";
dbCon.query(sql, [cookie], (err, result) => {
if (err) {
res.status(400).json({
message: "failed to get playlist details ",
});
} else {
let playlistSongs = [];
result.forEach((element, index) => {
const audio_id = element.audio_id;
dbCon.query(
"SELECT * FROM audios where video_id = ?",
[audio_id],
(err, song) => {
if (err) {
res.status(400).json({
message: "failed to get music",
});
} else {
playlistSongs.push(song);
}
});
});
console.log(playlistSongs);
res.status(200).json({
playlist: playlistSongs,
});
}
});
});
但是这里的问题是我尝试这样做我总是将 playlistSongs
作为一个空数组。
谢谢你。评论更正问题。
编辑:现在我知道问题与 javascript.
的执行有关
试试 async / await
:
playlist.post('/getplaylistSongs', async (req, res) => {
const { cookie } = req.body;
const sql = 'SELECT * FROM playlist WHERE user_id = ?';
try {
const result = await dbCon.query(sql, [cookie]);
let playlistSongs = [];
result.forEach(async (element, index) => {
const audio_id = element.audio_id;
const song = await dbCon.query(
'SELECT * FROM audios where video_id = ?',
[audio_id]
);
playlistSongs.push(song);
});
console.log(playlistSongs);
res.status(200).json({
playlist: playlistSongs,
});
} catch (e) {
res.status(400).json({
message: 'failed to get playlist details ',
});
}
});
我不知道问题出在哪里,我知道标题没有描述任何我对此表示歉意的内容。 这是我面临的问题。 我目前在 MERN 应用程序中工作。
我在 express 中有一条路线,我从两个表中请求数据库中的一些数据。
playlist.post("/getplaylistSongs", (req, res) => {
const { cookie } = req.body;
const sql = "SELECT * FROM playlist WHERE user_id = ?";
dbCon.query(sql, [cookie], (err, result) => {
if (err) {
res.status(400).json({
message: "failed to get playlist details ",
});
} else {
let playlistSongs = [];
result.forEach((element, index) => {
const audio_id = element.audio_id;
dbCon.query(
"SELECT * FROM audios where video_id = ?",
[audio_id],
(err, song) => {
if (err) {
res.status(400).json({
message: "failed to get music",
});
} else {
playlistSongs.push(song);
}
});
});
console.log(playlistSongs);
res.status(200).json({
playlist: playlistSongs,
});
}
});
});
但是这里的问题是我尝试这样做我总是将 playlistSongs
作为一个空数组。
谢谢你。评论更正问题。
编辑:现在我知道问题与 javascript.
的执行有关试试 async / await
:
playlist.post('/getplaylistSongs', async (req, res) => {
const { cookie } = req.body;
const sql = 'SELECT * FROM playlist WHERE user_id = ?';
try {
const result = await dbCon.query(sql, [cookie]);
let playlistSongs = [];
result.forEach(async (element, index) => {
const audio_id = element.audio_id;
const song = await dbCon.query(
'SELECT * FROM audios where video_id = ?',
[audio_id]
);
playlistSongs.push(song);
});
console.log(playlistSongs);
res.status(200).json({
playlist: playlistSongs,
});
} catch (e) {
res.status(400).json({
message: 'failed to get playlist details ',
});
}
});