Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Рыльских Алексей #60

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 33 additions & 3 deletions async.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,46 @@
* Сделано задание на звездочку
* Реализована остановка промиса по таймауту
*/
const isStar = true;
const isStar = false;

/** Функция паралелльно запускает указанное число промисов
* @param {Function<Promise>[]} jobs – функции, которые возвращают промисы
* @param {Number} parallelNum - число одновременно исполняющихся промисов
* @param {Number} timeout - таймаут работы промиса
* @returns {Promise<Array>}
*/
function runParallel(jobs, parallelNum, timeout = 1000) {
// асинхронная магия
function runParallel(jobs, parallelNum) {

if (jobs.length === 0) {
Promise.resolve(jobs);
}

let promiseArray = [];

function startPromise(index, currentJob, resolve) {

function addPromiseToArray() {

promiseArray[currentJob - 1] = jobs[currentJob - 1];

if (jobs.length === promiseArray.length) {
resolve(promiseArray);
} else {
startPromise(currentJob++, currentJob, resolve);
}
}

return (new Promise(() => {
jobs[currentJob - 1]()
.then(addPromiseToArray);
}));
}

return new Promise(resolve => {
for (let currentJob = 0; currentJob < parallelNum; currentJob++) {
startPromise(currentJob++, currentJob, resolve);
}
});
}

module.exports = {
Expand Down