Jonah Jonah - 1 year ago 96
Node.js Question

Why does node wait for a single promise, but not an array of promises?

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:


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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download