Skip to content

Instantly share code, notes, and snippets.

@chaseholdren
Last active May 27, 2019 02:45
Show Gist options
  • Select an option

  • Save chaseholdren/0375fd13675113040c0c21ee411bc205 to your computer and use it in GitHub Desktop.

Select an option

Save chaseholdren/0375fd13675113040c0c21ee411bc205 to your computer and use it in GitHub Desktop.
// In response to the following article:
// https://www.jimhribar.com/adventures-in-async-await/
//
// Using Javascripts Object.map function, it's possible to get an array of promises
// which can then be awaited simultaneously, which will execute all of them in parallel.
//
// This is faster than the looping approach in the article, which awaits each Promise individually.
//
// Console output:
// parallelJob: 501.226ms
// parallelJob: 2,2,2,2,2,2
// serialJob: 5011.910ms
// serialJob: 2,2,2,2,2,2
const double = function (value) {
return new Promise(resolve => {
setTimeout(function () {
resolve(value * 2);
}, 500);
});
};
const values = [1, 2, 1, 2, 1, 2, 1, 2, 2, 2];
const runSerialJob = (async () => {
const results = [];
const job = async () => {
for (let value of values) {
if ((await double(value)) == 4) {
results.push(value);
}
}
};
const timerLabel = "serialJob";
console.time(timerLabel);
job().then(() => {
console.timeEnd(timerLabel);
console.log(`${timerLabel}: ${results}`);
});
});
const runParallelJob = (async () => {
const job = async () => {
const doubledValueAndValuePromises = values.map(async (value) => {
const doubledValue = await double(value);
return {
value,
doubledValue
};
});
const listOfDoubledValueAndValue = await Promise.all(doubledValueAndValuePromises);
const results = listOfDoubledValueAndValue
.filter(doubledValueAndValue => doubledValueAndValue.doubledValue === 4)
.map(doubledValueAndValue => doubledValueAndValue.value);
return results;
};
const timerLabel = "parallelJob";
console.time(timerLabel);
const results = await job();
console.timeEnd(timerLabel);
console.log(`${timerLabel}: ${results}`);
});
runSerialJob();
runParallelJob();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment