Where Async/Await Matters

by jrab227

Babel + JSX

/* This is a hypothetical, yet common situation where we have to make an
 asynchronous call, that truely depends on two separate asynchronous calls. Specifically,
 the third request needs to access the results of the first request, but the main problem
 is storing the results to begin working on the second request. This is essentially where
 promises start to break, and the main benefit for async/await. As you will
 see, the problem is that the response of an async call is necessary in an async
 call later in the Promise chain, and this causes problems because we need state
 to store previous values so other callbacks can reference the state.
 
 Note this is just an example. Most of the time, if we are ever in a place where we need to
 send complex requests for model code, we should build out a new API endpoint to facilitate
 the requests in a single async call. If you're ever in a position where this is an issue for
 you, consider building the feature at the server level, since it's likely other people will
 need it too.
 */


/* Let's start with the two hypothetical Async calls we will need. Our fictitious application
 requires us to fetch a list of users that are part of active companies and active colors.
 The active companies and colors are determined by outside forces, so we need to fetch from a 
 database that maintains a list of active companies and active colors.
 */
let requestActiveCompanies = () => new Promise((resolve) => resolve([998]));

let requestActiveColors = () => new Promise((resolve) => resolve(["Green"]));

/* Now we set up our mock set of users.
 */

let Users = [{
  id: 0,
  color: "Blue",
  companyId: 999,
}, {
	id: 1,
  color: "Blue",
  companyId: 998,
}, {
	id: 2,
  color: "Red",
  companyId: 999,
}, {
	id: 3,
  color: "Red",
  companyId: 999,
}, {
	id: 4,
  color: "Green",
  companyId: 998,
}];

/* Here is the code that will take a list of companies and colors, and "fetch" the users
 that are part of the companies listed with the...