Skip to content

Instantly share code, notes, and snippets.

@lukehoban
Last active May 31, 2021 23:18
Show Gist options
  • Save lukehoban/0f366c5fd1af307b87da to your computer and use it in GitHub Desktop.
Save lukehoban/0f366c5fd1af307b87da to your computer and use it in GitHub Desktop.
Async/await and parallel loops
// ES6 w/ Promises
// Note: From a React starter template - see https://t.co/wkStq8y3I5
function fetchData(routes, params) {
let data = {};
return Promise.all(routes
.filter(route => route.handler.fetchData)
.map(route => {
return route.handler.fetchData(params).then(resp => {
data[route.name] = resp;
})
})
).then(() => data);
}
// ES7 with async/await and Promise.all
// Note: Starting to look a lot more like `normal` procedural code
// * But there's that one crazy line of "magic" for the parallel loop
async function fetchData(routes, params) {
let data = {};
await Promise.all(routes.map(async route => {
if(!route.handler.fetchData) return;
data[route.name] = await route.handler.fetchData(params);
}));
return data;
}
// ES? with async/await and hypothetical await*
// Note: This didn't help much.
// * Removed 12 characters
// * But complexity of having nested arrow function and map vs. for..of still there
async function fetchData(routes, params) {
let data = {};
await* routes.map(async route => {
if(!route.handler.fetchData) return;
data[route.name] = await route.handler.fetchData(params);
});
return data;
}
// ES?? with async/await and `asyncparallelfor..of
// Note: This actually makes things a lot simpler:
// * No need for a nested arrow function
// * Looks just like the procedural equivalent again
// * The downside is that it may not be obvious that the loop body executes non-sequentially
async function fetchData(routes, params) {
let data = {};
asyncparallelfor(route of routes) {
if(!route.handler.fetchData) return;
data[route.name] = await route.handler.fetchData(params);
};
return data;
}
@Jopie64
Copy link

Jopie64 commented Feb 28, 2018

What we need is 'await for' for RxJS like in Dart!
https://www.dartlang.org/tutorials/language/streams

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment