0

Let's say I have a collection of collections named, collections. Now, let's consider this piece of code.

_.each(collections, function(collection){
        _.each(collection, function(item){
           console.log(item);
        }
});

Several times, it prints undefined values. It seems to print item values before actually setting it from the previous loop. Why is it not retaining the order of execution?

Thanks in advance.

2
  • What are in the collections? The implementation of _.each shouldn't give that behaviour. Commented Feb 24, 2014 at 11:05
  • Did any of the answers help you? If so can you mark the correct one as answered. If not, can you clarify where you still have questions? Commented Mar 16, 2014 at 22:16

2 Answers 2

1

Are collections and collection plain arrays? Or are they Backbone.Collections?

The behavior you’re describing is not a bug in underscore. It should be maintaining the order of execution as you expect. This is probably an issue with the data in the collection.

If you want to strip all undefined values from your collection before running .each you can use _.compact(array) (assuming they are plain javascript arrays)

_.each(_.compact(collections), function(collection){
    _.each(_.compact(collection), function(item){
        console.log(item);
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

I think you're right about collection being a Backbone collection, in that case collection.each(function(item) { ... }) would be the Right Thing.
0

I guess that it is just because the inner loop also runs it's callback asynchronously. So the parent loop doesn't wait for it to complete, it runs straightaway the next iteration.

1 Comment

underscore's each implementation does not run it's callbacks asynchronously. It defaults to the native forEach if available.

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.