0

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!
    });
}

1 Answer 1

2

var video has functional scope. You want let video or const video, which have block scope.

Alternatively, moving the body of the loop to a separate function will create a new scope where video cannot be overwritten:

for (var video of videos) {
    downloadVideo(video)
}

function downloadVideo(video) {
    // ... your download logic
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.