Given the following code:
const ports = [null,3001];
function getPort(port)
{ return new Promise((resolve, reject) =>
{ // setTimeout to simulate getting port from OS
setTimeout(() =>
{ if(port < 3010)
{ return reject();
}
return resolve();
}, 2000);
});
}
ports.reduce(async (acc, port, index) =>
{ if(!port)
{ return;
}
try
{
const avail = await getPort(port);
return port;
}
catch(avail)
{ ports.push(++port);
}
});
Why is the reduce function only called for elements null and 3001 and not 3002 even though at the end of the reduce call the Array ports is equal to [null, 3001, 3002]?
Before the last reduce call completes, the original array already has a new element so why is it not called for that element as well?
The aim of the code is to try and find an available port starting at a given number and increment until we find one, or we hit an upper limit.
There are other ways of doing this, but the reduce method seemed the most succinct until I hit this dead end.
reduceis not the correct tool if you A) Aren't doing anything withacc, and B) Aren't using the return value ofreduce. The above is best done with a simple loop, notreduce.