Skip to content Skip to sidebar Skip to footer

For Loop Proceeding Out Of Order

new at this, please tell me if I'm leaving information out or anything like that. The code I'm working on can be seen here: http://codepen.io/hutchisonk/pen/mVyBde and I have also

Solution 1:

You are doing an asynchronous task in your loop. You should not expect those async tasks finish in the order that they have started.

The function getStreamingData is the one that I'm talking about.

Related: Asynchronous for cycle in JavaScript

This is one snippet that I wrote long time ago and I'm still using it in small projects. However there are many libraries out there which do the same plus many more.

Array.prototype.forEachAsync = function (cb, end) {
    var _this = this;
    setTimeout(function () {
        var index = 0;
        var next = function () {
            if (this.burned) return;
            this.burned = true;
            index++;
            if (index >= _this.length) {
                if (end) end();
                return;
            }
            cb(_this[index], next.bind({}));
        }
        if (_this.length == 0) {
            if (end) end();
        }else {
            cb(_this[0], next.bind({}));
        }
    }, 0);
}

It is not a good practice to touch the prototype like this. But just to give you an idea how you can do this ... After that code, you can loop over arrays asynchronously. When you are done with one element, call next.

var array = [1, 2, 3, 4]
array.forEachAsync(function (item, next) {
    // do some async taskconsole.log(item + " started");
    setTimeout(function () {
        console.log(item + " done");
        next();
    }, 1000);
}, function () {
    console.log("All done!");
});

Post a Comment for "For Loop Proceeding Out Of Order"