I have an array full of video objects. When I print them to the console, there are 30 elements - each an expected video object with the appropriate information. However, when I try to print an individual element of that array to the console, the console simply reads "undefined". Correspondingly, when I try to access the data of that element, an error is produced because the element is not defined. I'm using AJAX, but it should be noted that every single promise is guaranteed to be resolved by the time this function is called. Additionally, this is the very last part of the code. As such, I can't imagine how the array's contents would be changing. (And given that these are consecutive lines of code, it would additionally be surprising if this change was so reliable as to always happen between these two lines, even if it's something occurring asynchronously.)
The code:
var allVideoPromises = [];
Object.keys(channels).forEach((channelName) => {
var channel = channels[channelName];
channel.uploadsPromise.then(function(data) {
var videoList = JSON.parse(data);
var channelPromises = [];
for (var videoData in videoList.items) {
var video = new YouTubeVideo(videoList.items[videoData].contentDetails.videoId, channel);
channel.uploads.push(video);
videos.push(video);
channelPromises.push(video.videoPromise);
allVideoPromises.push(video.videoPromise);
video.videoPromise.then(function(data) {
var data = JSON.parse(data);
if (data.items.length > 0) {
var videoData = data.items[0];
video.title = videoData.snippet.title;
video.thumbnail = videoData.snippet.thumbnails.default;
video.buffer = (video.thumbnail.height > 90) ? (90 - video.thumbnail.height) / 2 : 0;
video.date = new Date(videoData.snippet.publishedAt);
video.loaded = true;
}
}).catch(function(err) { console.log(err); })
}
Promise.all(channelPromises).then(function(data) {
channel.uploads.sort(function(a, b) { if (a.date < b.date) return 1; else if (a.date > b.date) return -1; return 0; });
}).catch(function(err) { console.log(err); });
}).catch(function(err) { console.log(err); });
});
Promise.all(allVideoPromises).then(function(data) {
videos.sort((a, b) => a.date < b.date);
console.log(videos);
console.log(videos[0]);
//setVideo(mostRecent, video);
}).catch(function(err) { console.log(err); });
The output:
I have no clue what could be the issue here. It seems like the issue must be a basic JavaScript Issue, but in case it ends up being something else: I'm using HTML, CSS, JS, AJAX, and just enough JQuery to make these AJAX calls. I'm also using Google's YouTube API (v3), if that matters somehow. I'm not even using HTTP/HTTPS, as I'm just using this locally as a custom homepage. Any help would be appreciated.