Created
February 22, 2022 14:30
-
-
Save rusco/ebc3118bd6b17c83684f60a91226c3d9 to your computer and use it in GitHub Desktop.
parallel versus sequential promises in Javascript
This file contains 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
// jr | |
// parallel versus sequential promises in Javascript | |
// 22.02.2022 | |
const parallel = true; | |
const startTime = performance.now(); | |
console.clear(); | |
const asyncTimeout = (delay, data) => (new Promise(resolve => { setTimeout(() => resolve(delay, data), delay) })).then(d => `Waited ${d} seconds`); | |
const asyncFetch = (url) => fetch(url).then(response => (response.text())).then(text => `Fetched ${url}, and got back ${text}`); | |
const runTask = (spec) => (spec.task === 'wait') ? asyncTimeout(spec.duration) : asyncFetch(spec.url); | |
const asyncThingsToDo = [ | |
{ task: 'wait', duration: 1000 }, | |
{ task: 'fetch', url: 'https://jsonplaceholder.typicode.com/todos/2' }, | |
{ task: 'wait', duration: 2000 }, | |
{ task: 'fetch', url: 'https://jsonplaceholder.typicode.com/todos/1' }, | |
]; | |
if (parallel) { | |
const tasks = asyncThingsToDo.map(runTask); // Run all our tasks in parallel. | |
const results = await Promise.all(tasks); // Gather up the results. | |
results.forEach(x => console.log(x)); // Print them out on the console. | |
} else {//sequential: | |
const starterPromise = Promise.resolve(null); | |
const log = result => console.log(result); | |
await asyncThingsToDo.reduce((p, spec) => p.then(() => runTask(spec).then(log)), starterPromise); | |
} | |
console.log(`Task finished in ${Number.parseInt(performance.now() - startTime)} miliseconds `); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment