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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…