I have a nodeJS lambda function where I want to start 3 API calls immediately, but I receive an unknown number of items back from each API call, and I don't know how long each API call will take to execute. I have a specific priority of the items, so if the the first API call returns enough items, I don't care about the other 2 API calls.
I could just wait until the first one resolves to decide if I want to kick off the 2nd and 3rd API calls, but I like the idea of the calls being run in parallel and only awaiting them if required.
Is there anything wrong with starting all 3 API calls immediately and just returning early if I no longer care about the results of the other 2?
const getFiveThings = async () => {
const things = [];
const redThingsPromise = getRedThings();
const greenThingsPromise = getGreenThings();
const blueThingsPromise = getBlueThings();
const redThings = await redThingsPromise;
things.push(...redThings);
if (things.length >= 5) {
return things;
}
const greenThings = await greenThingsPromise;
things.push(...greenThings);
if (things.length >= 5) {
return things;
}
const blueThings = await blueThingsPromise;
things.push(...blueThings);
return things;
};