3 ms·
I was making the assumption that it was completely synchronous, and thus that using a new setTimeout per item wouldn’t be helpful, but I neglected to consider U
by chrismorgan 8y ago
I was making the assumption that it was completely synchronous, and thus that using a new setTimeout per item wouldn’t be helpful, but I neglected to consider UI responsiveness—and so on reflection such a thing might be useful. Taking that into account, it becomes rather messier:
new Promise(resolve => {
const out = [];
const iterator = collection[Symbol.iterator]();
function next() {
const item = iterator.next();
if (item) {
setTimeout(() => {
out.push(expensiveFunction(item.value));
next();
});
} else {
resolve(out);
}
}
next();
});
JavaScript’s threading model is rather hostile to expensive CPU-bound functions. Workers are just too hard to use unless you go all in with that architecture. I love being able to work with things like Rayon in Rust.