-1

I'm using a local database and Google API to build my own API, but I can't push objects into the "channels" array. I want the response to look something like this:

    [
       { id: 0, url: 'gwJ-mrP6_Ng', channelname: 'name1' },
       { id: 1, url: 'YPYwU2jeXIc', channelname: 'name2' },
       { id: 3, url: 'z3U0udLH974', channelname: 'name3' },
       { id: 2, url: 'AUHlDIuMLNY', channelname: 'name4' },
       { id: 4, url: 'vQEH_EksBbo', channelname: 'name5' }
    ]

And this is my code which I'm struggling with:

    app.get('/api/video/channels', (req, res) => {
        var channels = [];
        db.query(`SELECT video_url FROM videos`, (err, data) => {
            if (err) console.log(err);
            else {
                data.map((v, i) =>
                    axios.get(`https://www.googleapis.com/youtube/v3/videos?part=id%2C+snippet&id=${v.video_url}&key=${process.env.YT_API_KEY}`)
                        .then(res => channels.push({ "id": i, "url": v.video_url, "channelname": res.data.items[0].snippet.channelTitle }))
                )
                res.send(channels);
            }
        })
    })

console.log works, but the response always shows a blank array ( [] ). What is the problem with my code?

Thanks for your attention and help.

Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
Yumin Lee
  • 23
  • 4
  • That is because you are trying to do some async stuff inside of the map callback. You are returning a response to the caller before that async stuff completes, so the response is always an empty array. – Enrico Massone Feb 12 '22 at 09:08
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – jonrsharpe Feb 12 '22 at 09:13
  • 1
    I get the concept of what I was doing wrong, thank you @EnricoMassone – Yumin Lee Feb 12 '22 at 10:14
  • The question did help, although it feels a bit vague for me. But I get what the problem is, I'm just clearly not familiar with the concept. I should work on it. Thank you @jonrsharpe – Yumin Lee Feb 12 '22 at 10:19

1 Answers1

0

You have to use await to fulfill the result. try to change something like the below:

app.get('/api/video/channels', (req, res) => {
  var channels = [];
  db.query(`SELECT video_url FROM videos`, async (err, data) => {
    if (err) console.log(err);
    else {
      for (let i = 0; i < data.length; ++i) {
        let res = await axios.get(`https://www.googleapis.com/youtube/v3/videos?part=id%2C+snippet&id=${data[i].video_url}&key=${process.env.YT_API_KEY}`)
        channels.push({ "id": i, "url": data[i].video_url, "channelname": res.data.items[0].snippet.channelTitle });
      }
      res.send(channels);
    }
  })
})
Mostafa Fakhraei
  • 3,409
  • 3
  • 11
  • 25