Created
January 2, 2025 11:58
-
-
Save PetukhovArt/3dd8e6bb706a8a55f28b8244aeb3d0e0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Есть парочка функций, которые необходимо запустить параллельно | |
// а результат вернуть только тогда, когда обе они будут завершены | |
const fnA = (cb) => { | |
setTimeout(() => { | |
cb("a"); | |
}, 3000); | |
}; | |
const fnB = (cb) => { | |
setTimeout(() => { | |
cb("b"); | |
}, 1000); | |
}; | |
const runInParallel = (fns = [], cb) => { | |
let resultCount = 0 | |
const results = [] | |
if (!fns.length) return [] | |
for (let i = 0; i < fns.length; i++) { | |
const fn = fns[i] | |
if (typeof fn !== 'function') { | |
continue | |
} | |
new Promise((resolve, _) => fn(resolve)) | |
.then(result => { | |
console.log('resolved foo result:', `" ${result} "`) | |
resultCount++ | |
results.push(result) | |
if (resultCount === fns.length) { | |
cb(results) | |
} | |
}) | |
} | |
}; | |
runInParallel([fnA, fnB], console.log); | |
// ['b', 'a'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment