I have the following code, which works:
interface MyImages {
apple: HTMLImageElement,
banana: HTMLImageElement,
carrot: HTMLImageElement
}
async function fetchImages(): Promise<MyImages> {
const images = await Promise.all([
asyncImageLoad("/images/apple.png"),
asyncImageLoad("/images/banana.png"),
asyncImageLoad("/images/carrot.png")
]);
return {
apple: images[0],
banana: images[1],
carrot: images[2]
};
}
However, it's a bit verbose. Also, it's error-prone, because you have to match up the array indexes with the proper element.
I would much rather just do this:
async function fetchImages(): Promise<MyImages> {
return {
apple: await asyncImageLoad("/images/apple.png"),
banana: await asyncImageLoad("/images/banana.png"),
carrot: await asyncImageLoad("/images/carrot.png")
};
}
This is much more concise, less error-prone, but unfortunately it synchronously queries each image.
That is, instead of sending all requests at once, this one first queries for the apple, awaits for it to return, then queries for the banana, awaits for it to return, and then finally queries the carrot image.
Is there any way to have the ergonomics of the latter with the performance of the former?