1

I have a double nested loop on objects with _.each(). Depending on whether the second loop execution time, the result is very different. Here is the snippet:

var _ = require('underscore');

var user = {
  "data1": [1,2,3],
  "data2": ["a","b","c"]
};

var data={};
_.each(user,function(element,index){
  console.log(element);

  _.each(element,function(element,index){
    console.log(">>"+element);  // case 1
    //setTimeout(function(){ console.log(">>"+element); },2000);  // case 2
  });
});

Case 1 is what I like to achieve: element of data1 are displayed, before moving to data2 and displaying elements of data2. If a delay is introduced in displaying elements of dataX (comment case 1/un-comment case 2), then the dataX are all displayed together at the very end.

I was under the impression that _.each(element,function) would always wait the end of the execution of function before moving to the next element but that does not seem to be the case ...

Many thanks - C.

Christian68
  • 845
  • 4
  • 13
  • 24
  • `_.each` is synchronous. It runs straight through to the end. –  Oct 07 '16 at 17:19
  • 1
    Possible duplicate of [JavaScript, Node.js: is Array.forEach asynchronous?](http://stackoverflow.com/questions/5050265/javascript-node-js-is-array-foreach-asynchronous) –  Oct 07 '16 at 17:19

0 Answers0