Skip to content

Instantly share code, notes, and snippets.

@trivektor
Forked from lukehoban/asyncloops.js
Created January 10, 2017 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trivektor/a426c759786637610a1398d97249aefb to your computer and use it in GitHub Desktop.
Save trivektor/a426c759786637610a1398d97249aefb 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment