type OptionalArgs = | { saveInCache: (result: NonNullable) => Promise; fetchFromCache: () => Promise; } | { saveInCache?: undefined; fetchFromCache?: undefined; }; export async function fetchFromMultipleSources( fetchPromises: (() => Promise)[], args?: OptionalArgs, ) { let result = await args?.fetchFromCache?.(); if (result) { return result; } if (fetchPromises.length === 0) { throw new Error("fetchPromises cannot be empty"); } for (const promise of fetchPromises) { try { result = await promise(); if (result) break; } catch (e) {} } if (args?.saveInCache && result) { await args.saveInCache(result); } return result ?? null; }