Home > Net >  array.push doesn't seem to work on Nodejs Express
array.push doesn't seem to work on Nodejs Express

Time:02-12

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, 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.

CodePudding user response:

You have to use await for fulfill result, try to change something like bellow:

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