Is it safe to create unique object properties async in javascript?

Is the following code constructing the “shared” object in a correct way?

const shared = {};
const createUniqueField = async (value) => {
  shared[value] = await getDataFromSomeService(value);
};
await Promise.all(someArrayWithUniqueValues.map(value => createUniqueField(value)));

If not, what are the alternatives to do that?

Answer

It depends on what you mean by “safe” and “correct”, but the following approach might suit better:

const mapDataToValue = async (value) => {
  const data = await getDataFromSomeService(value);
  return { [value]: data };
};
const pairs = await Promise.all(someArrayWithUniqueValues.map(mapDataToValue));
const shared = pairs.reduce((merged, pair) => ({ ...merged, ...pair }), {});
  • Side-effect free,
  • Can’t end up in a state where shared is “half-built” (may not be the case with your approach either, depending on how you’re dealing with possible errors).

Leave a Reply

Your email address will not be published. Required fields are marked *