1

Consider this function which mocks querying a database, and returning some records after 2 seconds, via a Promise:

function query() {
  var recs = [1,2,3];
  return new Promise(r => setTimeout(() => r(recs), 2000))
}

If I add the following statement:

query().then(console.log);

and run the script the with node, it pauses 2 seconds, prints out the records, and returns, as expected.

On the other hand, if I replace that line with an array of the exact same promises:

Array(5).map(x => query().then(console.log));

The script returns immediately, and prints nothing. Why does node wait for the single promise to return before exiting, but exit immediately when there's an array of 5 unresolved promises?

Jonah
  • 15,806
  • 22
  • 87
  • 161
  • 1
    If you want to wait one resolved promise to execute another this post would like you : http://stackoverflow.com/questions/37578795/implementing-promise-series-as-alternative-to-promise-all – Jose Hermosilla Rodrigo Jun 03 '16 at 03:37

1 Answers1

1

It's because Array(5).map(... will never call the function passed to map. The reason is that map skips holes in the array. Array(5) returns what is called a sparse array, and has only empty slots but no actual content.

For more information about sparse arrays and how to turn them into dense arrays I would recommend this excellent blog post by Axel Rauschmayer.

Jon Koops
  • 8,801
  • 6
  • 29
  • 51