R
R
r2sada2r2015-04-12 08:19:28
Node.js
r2sada2r, 2015-04-12 08:19:28

Why doesn't iterate over the entire array?

var arr = [];
arr[0] = 'sda21g';
arr[5] = 'g42c';
arr[8] = '09-sdq3';
arr[10] = 'm/xndhi';

console.log(arr);

async.each(arr, function(el, callback){
  console.log('----------------------------');
  console.log(el);
  console.log('----------------------------');
  
  callback();
},

function(err) {
  console.log('Прошли все элементы массива arr');
});

Output:
[ 'sda21g', , , , , 'g42c', , , '09-sdq3', , 'm/xndhi' ]
-------------------- --------
sda21g
----------------------
------------- ---------------
g42c
----------------------
------ ----------------------
09-sdq3
-------------------------
-----------------------------
m/ xndhi
---------------- ------------
If there are no empty elements in the array, then everything is fine. Most likely, all callbacks in async.each do not go through ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya Shatokhin, 2015-04-13
@r2sada2r

Async will call the final callback only when all iterations of the array have passed, where the number of iterations for it is the length of the array. According to the JS specification, the length of the array is the index of the last element + 1. In the example, a sparse array is specified, and async uses Array.forEach to iterate, which skips missing indices, respectively, the final callback will never be called.
To get out of this situation, you can (optionally) :

  • avoid sparse arrays
  • wait for the release of Async 0.10, which will abandon Array.forEach in favor of a simple for loop (there is a corresponding commit in the master branch)
  • switch to alternative (100% compatible) neo_async library

M
Maxim Antonikhin, 2015-04-12
Antonikhin @STJ

Empty cells in array == undefined

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question