DEV Community

[Comment from a deleted post]
Collapse
 
pdamra profile image
Philip Damra

This isn't an anti-pattern, and you don't need write it like this. Just use:

const [states, addressTypes, phoneTypes] = await Promise.all([GetAllStates(), FetchAddressTypes(), FindPhoneTypes()]);

Collapse
 
rebeccastevens profile image
Rebecca Stevens • Edited

For this particular case, Promise.allSettled() would be probably be preferable.

Though I guess it depends on how you want to do error handling.

Collapse
 
djheru profile image
Philip Damra

Yes, I would agree. I posted a similar comment down below. If the async functions we're calling do their own error handling, then it may not be necessary, but if they don't, or you're not sure, it's good to have the result data provided by allSettled()

Collapse
 
peq profile image
Peter Zeller • Edited

That looks really ugly to me. You have to read it left, right, left right, left, right.

You'll probably also lose all typing information if you do it like this (although TypeScript already can type a lot of stupid Javascript idioms).

Collapse
 
djheru profile image
Philip Damra • Edited

It's not a stupid idiom, it's just passing an array to an async function and receiving an array as a return value. If it's easier for you, you can type

const getAllStatesPromise = GetAllStates();
const fetchAddressTypesPromise = FetchAddressTypes();
const findPhoneTypesPromise = FetchPhoneTypes();

const promisesToAwait = [
  getAllStatesPromise, 
  fetchAddressTypesPromise, 
  findPhoneTypesPromise 
];

const resolvedPromises = await Promise.all(promisesToAwait);

const states = resolvedPromises[0];
const addressTypes = resolvedPromises[1];
const phoneTypes = resolvedPromises[2];

but why would you want to do that???