Kousha Kousha - 6 days ago 6
Javascript Question

Javascript new Operator inside a for loop

Here is a the simplest function:

module.exports = function Dummy(id) {
this.id = id;

this.delay = function() {
return new Promise(function (resolve, reject) {
// Do some stuff async
// once done
resolve();
});
}
}


I want to instantiate a few instances of this
Dummy()
class inside a for loop:

for (var i = 0; i < 3; i++) {
var id = "id_" + i;
var dummy = new Dummy(id);

dummy
.delay()
.then(function () {
console.log(dummy.id);
});
}


However, all of these print
id_2
; its as though the instant
dummy
is overwritten, even though I am instantiating the variable
var dummy
every time inside the
for
loop.

Help is appreciated.

Answer

There is a closure problem with the variable called dummy inside the then function. The value will be the last iterated because every iteration of the for will override the previous one. It means that when the then function is executed asynchronously (due to the promise you are using) the value of the dummy var will be the last value assigned during the loop.

To fix it I suggest to simply do this instead:

for (var i = 0; i < 3; i++) {
    (function (id) { //Creates a simple new scope
        var dummy = new Dummy(id);

        dummy
            .delay()
            .then(function () {
                console.log(dummy.id);
            });
    })("id_" + i);
}

There are lots of ways to fix this but I think that is the simplest for your current code.

As you may noticed, for every for iteration I have created a new scope. When the then function is executed, it will access to the dummy var in that scope.

Comments