7

Im working with the gm npm module that deals with image manipulation. and i have this code.

for(i=0;i < 4;i++){
    gm("www/img/" + image[i]).crop(550, 406, 0, 0).write(function(err) {
         console.log(this.outname + " created  ::  " + arguments[3]); //success
    });
}

this loop is meant to loop through the images array and crop each photo, but it only crops the last one. i think its something to do function invocation and callbacks, but not advanced yet for that level.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Unknown
  • 257
  • 1
  • 3
  • 10

2 Answers2

7

Change your code to:

for (var i = 0; i < 4; i++) {
  (function (i) {
    gm("www/img/" + image[i]).crop(550, 406, 0, 0).write(function(err) {
         console.log(this.outname + " created  ::  " + arguments[3]); //success
    });
  }).call(this, i);
}

otherwise the value of i will be 3 each time your callback is being invoked.

Minko Gechev
  • 25,304
  • 9
  • 61
  • 68
5

You need to create a "closure" over the variable

Js has a function scope.

for (i = 0; i < 4; i++)
{
    (function (a)
    {
        gm("www/img/" + image[a]).crop(550, 406, 0, 0).write(function (err)
        {
            console.log(this.outname + " created  ::  " + arguments[3]); //success
        });
    }).call(this,i)
}

or

that=this;

for (i = 0; i < 4; i++)
    {
        (function (a)
        {
            gm("www/img/" + image[a]).crop(550, 406, 0, 0).write(function (err)
            {
                console.log(that.outname + " created  ::  " + arguments[3]); //success
            });
        })(i)
    }

edit :

Also - I would also keep a reference to the arguments since now , after IIFE - the arguments is changing.

you can keep your arguments via :

var args= Array.prototype.slice.apply(arguments)

example :

function g()

{
for (i = 0; i < 4; i++)
    {
        (function (a)
        {
           console.log(arguments); //huh ? arguments are not a,b,c !!! anymore
        })(i);
    }
}


g('a','b','c') // 0,1,2,3

so you do need to keep reference to the arguments cuz their changed after IIFE.

Royi Namir
  • 144,742
  • 138
  • 468
  • 792