Skip to content

Instantly share code, notes, and snippets.

@PetukhovArt
Created January 2, 2025 11:58
Show Gist options
  • Save PetukhovArt/3dd8e6bb706a8a55f28b8244aeb3d0e0 to your computer and use it in GitHub Desktop.
Save PetukhovArt/3dd8e6bb706a8a55f28b8244aeb3d0e0 to your computer and use it in GitHub Desktop.
// Есть парочка функций, которые необходимо запустить параллельно
// а результат вернуть только тогда, когда обе они будут завершены
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