我可以同步运行ytdl getInfo()吗?

时间:2019-09-26 17:57:28

标签: javascript node.js asynchronous synchronous

我正在使用ytdl-core和youtube-playlist制作YouTube播放列表下载器。我想列出播放列表中的所有标题。这是我的代码:

ytlist(playlist_url, 'url').then(res => {

    var video_url = res.data.playlist;
    var total_files = video_url.length;

    video_url.forEach(function(url, index) {
        ytdl.getInfo(url, (err, info) => {
            console.log(index + " : " + info.title);
        });
    });
});

当我启动此代码以提供指向播放列表的链接时,就会发生这种情况:

7 : C418 - Minecraft - Minecraft Volume Alpha
3 : C418 - Death - Minecraft Volume Alpha
4 : C418 - Living Mice - Minecraft Volume Alpha
19 : C418  - Dog - Minecraft Volume Alpha
14 : C418 - Chris - Minecraft Volume Alpha
17 : C418  - Sweden - Minecraft Volume Alpha
16 : C418 - Excuse - Minecraft Volume Alpha
15 : C418 -  Thirteen - Minecraft Volume Alpha
22 : C418 - Droopy likes Ricochet - Minecraft Volume Alpha
20 : C418 - Danny - Minecraft Volume Alpha
0 : C418 - Key - Minecraft Volume Alpha
21 : C418 - Beginning - Minecraft Volume Alpha
8 : C418 - Oxygène - Minecraft Volume Alpha
9 : C418 - Équinoxe - Minecraft Volume Alpha
2 : C418 - Subwoofer Lullaby - Minecraft Volume Alpha
12 : C418 - Wet Hands - Minecraft Volume Alpha
18 : C418 - Cat - Minecraft Volume Alpha
10 : C418 - Mice on Venus - Minecraft Volume Alpha
..... and so on

播放列表中的项目应从0开始,但不是。 我意识到ytdl-core lib是异步的,但我不知道如何使其同步。你能帮助我吗?抱歉,格式错误。这是我的第一个问题。

1 个答案:

答案 0 :(得分:0)

const ytdl = require('ytdl-core');

const video_url = [
    'hxOI7wahw7w', // [MV] HONG JIN YOUNG(홍진영) _ Boogie Man(부기맨)
    'iOxzG3jjFkY', // Willy William - Ego (Clip Officiel)
    'WGclLoxZz18', // GZUZ - Drück Drück (feat. LX)
    '5WujFgnZAko'  // Lozano - Kako tebe nema druga (2015)
];

let task = [];

video_url.forEach(url => task.push(ytdl.getInfo(url)));

Promise.all(task).then(res => {
    for (let r in res) {
        console.log(`${r} : ${res[r].title}`);
    }
});

帖子已更新