0

I have a gulpfile with constant PATH object. One of its fields is array. I want to iterate through it and assign different watch to react with different tasks. But when I try it assing task in loop:

  for(var i = 0; i < PATH.PHP[i].MODULE.length; i++){
  gulp.task('sync-'+PATH.PHP[i].MODULE, function(){
    return gulp.src(PATH.PHP[i].IN)
      .pipe(newer(PATH.PHP[i].OUT))
      .pipe(gulp.dest(PATH.PHP[i].OUT));
  });
}

PATH.PHP[i] is not defined within anonymous function. The reason I need it because if I watch whole folder it takes too much time syncing it with remote, if preprocessed through plugins like "gulp-newer" and "gulp-changed".

0xCAFEBABE
  • 17
  • 1
  • 6
  • Well, it is obviously an error, but it doesn't change the fact that PATH constant is not visible within anonymous function :( – 0xCAFEBABE Apr 25 '16 at 08:00
  • If I pass simple string instead of variable field it works, so I'm pretty sure it is namespace issue. – 0xCAFEBABE Apr 25 '16 at 08:01
  • Possible duplicate of [using anonymous function in javascript for loops](http://stackoverflow.com/questions/13977046/using-anonymous-function-in-javascript-for-loops) – Ondrej Svejdar Apr 25 '16 at 08:02

1 Answers1

0

The problem is the asynchronous function call inside the for loop. When the callback fires it is most likely already at it's final value, so every callback is called with the same value i.

You need to wrap the async function call inside a new function, to ensure that the value of i is as intended in each callback. Try this pattern:

for(var i = 0; i < PATH.PHP[i].MODULE.length; i++){
  (function(i){
    gulp.task('sync-'+PATH.PHP[i].MODULE, function(){
      return gulp.src(PATH.PHP[i].IN)
        .pipe(newer(PATH.PHP[i].OUT))
        .pipe(gulp.dest(PATH.PHP[i].OUT));
    });
  })(i);
}
birnbaum
  • 4,718
  • 28
  • 37