YaSh Chaudhary YaSh Chaudhary - 9 months ago 93
Node.js Question

variable undefined outside youtube search api function

I am fetching playlistId from youtube api .

It gives correct output when console output within the youtube search function.

It gives undefined outside youtube search api function.

var playlistId;
async function suggestTrack(genre) {

youtube.search.list({
auth: config.youtube.key,
part: 'id,snippet',
q: genre
}, function (err, data) {
if (err) {
console.error('Error: ' + err);
}
if (data) {
console.log(data.items[0].id.playlistId); //getting the id
playlistId = data.items[0].id.playlistId;

}
//process.exit();
});

console.log(playlistId);// undefined

const tracks = await youtube_api.getPlaylistTracks(playlistId);
return tracks[Math.floor(tracks.length * Math.random())];

}

Answer Source

The API call is asynchronous. And you are printing the value of playlistId before the response of the api even comes back. You have to wait for the response to come. And since you are using async wrap the api call in a Promise and use await. To promisify the search.list method, you have a lot of options, or you can do it yourself, like below

function search(key, part, genre) {
  return new Promise((resolve, reject) => {
    youtube.search.list({
      auth: key,
      part: part,
      q: genre
    }, function (err, data) {
      if (err) {
        reject(err);
        return;
      }
      // use better check for playlistId here
      resolve(data ? data.items[0].id.playlistId : null);
    })
  });
}

// then use it here
async function suggestTrack(genre) {
  const playlistId = await search(config.youtube.key, 'id,snippet', genre);      
  const tracks = await youtube_api.getPlaylistTracks(playlistId);
  return tracks[Math.floor(tracks.length * Math.random())];
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download