gpt4 book ai didi

javascript - JS : Calling async function in for loop does not reference the same iterated variable

转载 作者:行者123 更新时间:2023-12-01 00:54:49 26 4
gpt4 key购买 nike

我正在 Node.js 中创建一个队列来下载 YouTube 视频。触发下载后,所有排队的视频应同时开始下载。只需从数据库中获取所有排队的视频并在 for 循环中迭代它们即可处理此问题。但是,当我的下载完成时,我无法在数据库中将其标记为如此,因为“视频”现在引用了我的 for 循环中的最后一个视频。我该如何解决这个问题?

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

最佳答案

var video 具有功能范围。您需要具有 block 作用域的 let videoconst video

或者,将循环体移动到单独的函数将创建一个新的作用域,其中 video 无法被覆盖:

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

function downloadVideo(video) {
// ... your download logic
}

关于javascript - JS : Calling async function in for loop does not reference the same iterated variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56676899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com