0

I don't know what the problem is so, i know the title doesnot describes anything my appologies for that. Here is the problem I am facing. I am currently working in a MERN app.

I have a route in express where i request for some data from the database from two tables.

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,
      });
    }
  });
});

but the problem here is however i try to do it i always get the playlistSongs as an empty array. thank you. comment for correcting the question.

EDIT : Now i know the problem is realted to execution of the javascript.

1 Answers1

0

Try with 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 ',
    });
  }
});
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29
  • Thank you for responding i appreciate the help but got a syntax error, would you mind having a look at it ` const song = await dbCon.query( ^^^^^ SyntaxError: await is only valid in async functions and the top level bodies of modules` –  Feb 16 '22 at 13:40
  • I forgot to put the declare the inner `forEach` function as `async`. Check the edited answer. – lpizzinidev Feb 16 '22 at 16:21