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.

6
  • 1
    Shouldn't your logic be in the callback function of User.find? As in User.find({'twitter.id':collected[i].author}, function(user) { /* logic */ }); Commented Nov 23, 2015 at 20:51
  • Shouldn't async.parallel be outside the while loop? Commented Nov 23, 2015 at 20:51
  • 1
    @epascarello: "The async part of this loop is usually outside the loop. I did this to debug the reason" Commented Nov 23, 2015 at 20:53
  • @nathanleung I'm prepared the query beforehand, it still works the same way in execution. Commented Nov 23, 2015 at 20:54
  • 1
    Sounds like the classic: stackoverflow.com/questions/750486/… Commented Nov 23, 2015 at 20:56

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Could you give a little example on how this would be coded?
There are so many examples in the linked question. E.g. stackoverflow.com/a/19324832/218196 .
Code's working great now, very quick solution. Lesson learned. Closures and scopes.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.