Without changing your example a lot you could use then
to set a callback that sets the property when resolved. Store the resulting promise inside an array so you know when all promises are finished.
const promises = [];
if (!output.valueA) {
promises.push(getValueA().then(value => output.valueA = value));
}
if (!output.valueB) {
promises.push(getValueB().then(value => output.valueB = value));
}
await Promise.all(promises);
You can use a more dynamic aproach by defining the properties to check and their async getters up front. An example could be:
const asyncGetters = [["valueA", getValueA], ["valueB", getValueB]];
await Promise.all(
asyncGetters
.filter(([prop]) => !output[prop])
.map(async ([prop, asyncGetter]) => output[prop] = await asyncGetter())
);
Here filter
acts like your if
statement, selecting only the elements that have a falsy value. map
will make sure to collect the promises of the async map
callbacks, so you can use await Promise.all()
to wait for them all to finish.