0
\$\begingroup\$

I currently use setInterval and a wait flag to process this collection. Is there a cleaner way?

var wait = false;
var processInterval = setInterval(function(){
    if(!wait){
        var currentVideo = videos.shift();

        if(currentVideo){
            wait = true;

            validateSongById(currentVideo.videoId, function(result){
                wait = false;
                if(result){
                    clearInterval(processInterval);
                    callback(currentVideo);
                    return;
                }
            });
        }
    }
}, 200);
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You're basically there, I would say. If the validateSongById function works as expected, it'll call its callback when it's done, and you then do it again for the next video.

function processVideos(videos, callback) {
    var results = [], i = 0;
    function processNext() {
        if(i < videos.length) {
            validateSongById(videos[i].videoId, function (result) {
                results.push(result);
                i++;
                processNext();
            });
        } else {
            callback(results); // when called, all the videos have been processed
        }
    }
    processNext(); // start the processing
}

With this, you call processVideos with the videos array and a callback. The callback is called with a new array of all the results.

Alternatively, you can attach the result to the video-object directly, so the video and the result are tied together:

function processVideos(videos, callback) {
    var i = 0;
    function processNext() {
        if(i < videos.length) {
            validateSongById(videos[i].videoId, function (result) {
                videos[i].result = result;
                i++;
                processNext();
            });
        } else {
            callback(); // when called, all the videos have been processed
        }
    }
    processNext(); // start the processing
}
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.