update: better parallel

This commit is contained in:
KoroLion 2021-05-18 21:50:59 +03:00
parent ed0a398a63
commit 2db3b98a85

View File

@ -1,7 +1,5 @@
// Параллельные вычисления // Параллельные вычисления
const WAIT_CHECK_TIME = 10;
function parallel(promises, callback) { function parallel(promises, callback) {
const result = []; const result = [];
@ -9,7 +7,11 @@ function parallel(promises, callback) {
const setResult = (i, res) => { const setResult = (i, res) => {
done++; done++;
result[i] = res; result[i] = res;
if (done === promises.length) {
callback(result);
} }
}
for (let i in promises) { for (let i in promises) {
const promise = promises[i]; const promise = promises[i];
const res = promise((res) => setResult(i, res)); const res = promise((res) => setResult(i, res));
@ -17,20 +19,6 @@ function parallel(promises, callback) {
setResult(i, res); setResult(i, res);
} }
} }
// if all sync
if (done === promises.length) {
callback(result);
return;
}
// if at least one is async
const waitInterval = setInterval(() => {
if (done === promises.length) {
clearInterval(waitInterval);
callback(result);
}
}, WAIT_CHECK_TIME);
} }
parallel([ parallel([