I am creating a queue to download YouTube videos in Node.js. When the download is triggered all queued videos should start downloading simultaneously. This is handled simply by getting all the queued videos from the database and iterating over them in a for loop. However when my download finishes I cannot mark it as so in the database because because "video" now references the last video in my for loop. How do I resolve this?
...
var videos = db.videos.find({ status: 'queued' });
for (var video of videos) {
alert(video.id); // This is the correct id
var download = ytdl(`http://www.youtube.com/watch?v=${video.id}`);
download.pipe(fs.createWriteStream(filename));
download.on('end', () => {
video.status = 'done';
db.videos.update(video)
alert(video.id); // This is now the id of the last video in videos!
});
}