NodeJS - how to make forEach and for loop functions sequential

Viewed 7107
server.queue.forEach(function(q) {
    YTDL.getInfo(q, (error, info) => {
        console.log(info["title"]);
        message.reply('"' + info["title"] + '"');
    });
});

for (var i = 0; i < server.queue.length; i++) {
    YTDL.getInfo(server.queue[i], (error, info) => {
         console.log(info["title"]);
         message.reply('"' + info["title"] + '"');
    });
}

I'm creating a music bot for a VoIP called Discord using Node.js and whenever either of the loops above execute, they print in a random order. How do I make it so that they are printed sequentially (server.queue[0], server.queue[1], server.queue[2]...)? YTDL is a package called ytdl-core that downloads YouTube videos as well as display the info such as the title of a video using the video link. server.queue is an array of YouTube video links.

3 Answers

I was struggling with this problem for a while to find the best solution until I found out the built-in yield feature represented in ECMA6. so using gen-run library you can do the following:

let run = require('gen-run');

function notSequential(){
    for (let i = 0; i < 3; i++)
        f(i * 1000);
    console.log("it won't print after for loop");
}

function sequential(){
    run(function*(){
        for (let i = 0; i < 3; i++)
            yield changedF(i * 1000);
        console.log("it will print after for loop");
    });
}

function f(time) {
    setTimeout(function(){
        console.log(time);
    }, time);
}

function changedF(time) {
    return function (callback) {
        setTimeout(function(){
            console.log(time);
            callback();
        }, time);
    }
}

notSequential();

it won't print after for loop 0 1000 2000

sequential();

0 1000 2000 it will print after for loop

Related