Created
September 5, 2023 15:56
-
-
Save moritzsalla/6ba54566caac43e205d746d5573fb557 to your computer and use it in GitHub Desktop.
concurrent-fetch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { suppressConsoleLogs } from "test/utils/suppressConsoleLogs"; | |
import { concurrentFetch } from "./concurrentFetch"; | |
describe("concurrentFetch", () => { | |
it( | |
"should return an array of resolved values", | |
suppressConsoleLogs(async () => { | |
const result = await concurrentFetch( | |
Promise.resolve("value1"), | |
Promise.reject("error1"), | |
Promise.resolve("value2"), | |
Promise.reject("error2") | |
); | |
const expected = ["value1", undefined, "value2", undefined]; | |
expect(result).toEqual(expected); | |
}, "warn") | |
); | |
it( | |
"should return an empty array if all promises are rejected", | |
suppressConsoleLogs(async () => { | |
const result = await concurrentFetch( | |
Promise.reject("error1"), | |
Promise.reject("error2"), | |
Promise.reject("error3") | |
); | |
expect(result).toEqual([undefined, undefined, undefined]); | |
}, "warn") | |
); | |
it( | |
"should return an empty array if no promises are passed", | |
suppressConsoleLogs(async () => { | |
const result = await concurrentFetch(); | |
expect(result).toEqual([]); | |
}, "warn") | |
); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Waits for all promises to settle and returns an array of resolved values. | |
* | |
* @param promises The promises to settle. | |
* | |
* @returns A promise that resolves to an array of resolved values. | |
* | |
*/ | |
export const concurrentFetch = async <T extends unknown[]>( | |
...promises: { [K in keyof T]: Promise<T[K]> } | |
) => { | |
// Wait for all promises to resolve (at once). | |
const results = await Promise.allSettled(promises); | |
const resolvedPromises = results?.map((response) => { | |
// filter out promises that didn't resolve | |
if (response.status !== "fulfilled") { | |
console.warn( | |
`Promise rejected: ${response.reason} (${response.status}). Failing silently.` | |
); | |
return undefined; | |
} | |
return response.value; | |
}); | |
return resolvedPromises as Partial<T>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment