Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
How to make this variable execture after i get the data?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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 ',
    });
  }
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!