Async / await over array

by Ford Heacock

JavaScript

// need to asynchronously fetch things then fire off foo in its results


async function searchZip() {
	let things = [1,2,3];
  return foo(await Promise.all(things));
}

async function foo(things) {
  const results = [];
  for (const thing of things) {
    // Good: all asynchronous operations are immediately started.
    let bar = await $.get(`https://jsonplaceholder.typicode.com/users/${thing}`);
    
    // return array of store ids
    results.push(bar);
  }
  // Now that all the asynchronous operations are running, here we wait until they all complete.
  return baz(await Promise.all(results));
}

async function baz(stores) {
	const results = [];
  for (const thing of stores) {
  	let store = await thing.name;
    results.push(store);
  }
  return results;
}

function doTheThing() {
  searchZip().then(data => console.log(data))
    .catch(reason => console.log(reason.message));
}

doTheThing();