I m making a music website. I want to make a trending section. To make that trending section I m using YouTube API to get the no. of views. So here first I m calling my database in which album data is stored. In that one field is such that stores the id of song present in that album. So using that id, I m running a function which gives me no. of views. I am storing that song's id and views in arr_song and arr_views respectively. I then want to export this arr_song and arr_views in my main index file. But the problem is the data is stored in array but as it is a promise the data is getting stored in arr_song and arr_views late and before only it runs in my main index.js file. So eventually it shows me array with nothing. I want to export stored array data in my index.js file.
const axios = require("axios").default;
var url =
"https://youtube.googleapis.com/youtube/v3/videos?part=statistics&id=";
var key = "&key=AIzaSyDwUGeRKMTCeslgQjETBgP1ozqlB0yX9s0";
var id = "sAzlWScHTc4";
var final_url;
var arr_song = [];
var arr_views = [];
function getYTData(songId) {
final_url = url + songId + key;
axios.get(final_url).then(res => {
const yt_data = res.data;
console.log(songId);
console.log(yt_data.items[0].statistics.viewCount);
arr_song.push(songId);
arr_views.push(yt_data.items[0].statistics.viewCount);
});
}
function getting_data() {
axios.get("http://localhost:8000/albums/").then(res => {
const album_data = res.data;
for (var i = 0; i < album_data.length; i++) {
for (var j = 0; j < album_data[i].songs_id.length; j++) {
getYTData(album_data[i].songs_id[j]);
}
}
});
}
getting_data();
const ArrSong = arr_song;