0

Near the end of the look where you see console.log(authors), the array is constantly overwriting itself. The async part of this loop is usually outside the loop. I did this to debug the reason why I get a big array full of the same username, rather than an array full of a series of different usernames. This is the code I have:

while (i >= 0) {
  var search = User.find({'twitter.id' : collected[i].author});

  search.limit(1);
  searches.push(function(cb) {
    search.exec(function (err, hold){
      if (err) cb(err, null);
      else {
        cb(null, hold[0].twitter.username);
      }
    });
  });
  i = i - 1;

  async.parallel(searches, function( err, authors) {
    if ( err ) return console.error( err );
    else {
      console.log(authors);
    }
  });
}

These are the results I get:

results

It's been a long day, I'm not quite seeing where I'm going wrong.

sodawillow
  • 12,497
  • 4
  • 34
  • 44
Gregory Worrall
  • 181
  • 2
  • 16

2 Answers2

1

The issue is that at the moment the task function (function(cb) { ... }) is called, search already has a different value, the value of the last iteration. All the tasks refer to the same search variable and therefore perform the same search.

This is the typical "closure inside loop" problem.

You need to create scope per iteration. See JavaScript closure inside loops – simple practical example for solutions.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

you are not clearing Searches...

so every itteration go like:

  1. add a search to searches
  2. run all searches (write to log)

1st itteration: 1st search.

2nd itteration: 1st search + 2nd search.

3rd itteration: 1st search + 2nd search + 3rd search.

you might wanted to run the async.parallel() after the while ends.

Tomer W
  • 3,395
  • 2
  • 29
  • 44