Async Promises in Parallel
Concurrency is when two or more tasks can start, run, and complete in overlapping time periods. It doesnot necessarily mean they will ever both be running at the same instant. Multitasking on a Single-core Processor.
Parallelism is when tasks literally run at the same time. Multitasking on a Multi-core Processor.
forEach run in Parallel.
function asyncParallel(promises, callback) {
const results = [];
const errors = [];
let completed = 0;
promises.forEach((promise) => {
promise
.then((res) => {
results.push(res);
})
.catch((val) => {
errors.push(val);
})
.finally(() => {
completed++;
if (completed === promises.length) {
callback(results, errors);
}
});
});
}
function asyncParallel(promises, callback) {
const results = [];
const errors = [];
let completed = 0;
promises.forEach(async (promise) => {
try {
const res = await promise;
results.push(res);
} catch (e) {
errors.push(e);
} finally {
completed++;
if (completed === promises.length) {
callback(results, errors);
}
}
});
}
function asyncParallel(promises, callback) {
const results = [];
const errors = [];
let completed = 0;
promises.forEach((promise) => {
promise
.then((res) => {
results.push(res);
})
.catch((val) => {
errors.push(val);
})
.finally(() => {
completed++;
if (completed === promises.length) {
callback(results, errors);
}
});
});
}
function createAsyncTask(value) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (value < 5) {
reject("Error: " + value);
} else {
resolve(value);
}
}, value * 1000);
});
}
let tasks = [
createAsyncTask(4),
createAsyncTask(1),
createAsyncTask(7),
createAsyncTask(2),
createAsyncTask(9),
createAsyncTask(6),
];
asyncParallel(tasks, (results, errors) => {
console.log("Result", results);
console.log("Error", errors);
});
// Result [ 6, 7, 9 ]
// Error [ 'Error: 1', 'Error: 2', 'Error: 4' ]