ihackalot
7/29/2017 - 4:52 PM

Async/await and parallel loops

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;
}