Skip to content

Instantly share code, notes, and snippets.

@themgoncalves
Created May 26, 2021 15:28
Show Gist options
  • Save themgoncalves/a3c654e06dac2e77529f43d37092311d to your computer and use it in GitHub Desktop.
Save themgoncalves/a3c654e06dac2e77529f43d37092311d to your computer and use it in GitHub Desktop.
JavaScript and Asynchronous Operations: Do you really do it right?
/** BAD, BLOCKS THE EXECUTION */
async function getOptions() {
// request "toppings" and wait for the response
// only then goes to the next line
const toppings = await getToppings();
const condiments = await getCondiments();
const buns = await getBuns();
return { toppings, condiments, buns };
}
/** GREAT, TAKE BENEFIT FROM ASYNC OPS */
async function getOptions() {
// request all methods asynchronously
// and only resolves after all methods have either fulfilled or rejected
const [toppings, condiments, buns] = await Promise.allSettled([
getToppings(),
getCondiments(),
getBuns(),
]);
return { toppings, condiments, buns };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment