Last active
October 23, 2024 22:27
-
-
Save kirkegaard/b46040a430293d11e16458371b2ee602 to your computer and use it in GitHub Desktop.
Fetch multiple endpoints in parallel
This file contains 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
const fetcher = async (path, options = {}) => { | |
const response = await fetch(path, options); | |
if (!response.ok) { | |
throw new Error(`HTTP error! status: ${response.status}`); | |
} | |
const data = await response.json(); | |
return data; | |
}; | |
const parallelFetcher = async (paths) => { | |
const promises = Object.entries(paths).map(async ([key, promise]) => { | |
try { | |
const result = await promise; | |
return { [key]: result }; | |
} catch (error) { | |
return { [key]: { error: error.message } }; | |
} | |
}); | |
const results = await Promise.allSettled(promises); | |
return results.reduce((acc, curr) => { | |
const [key, value] = Object.entries(curr.value)[0]; | |
acc[key] = value; | |
return acc; | |
}, {}); | |
}; | |
// Usage example | |
const data = await parallelFetcher({ | |
ditto: fetcher("https://pokeapi.co/api/v2/pokemon/ditto"), | |
pikachu: fetcher("https://pokeapi.co/api/v2/pokemon/pikachu"), | |
charmander: fetcher("https://pokeapi.co/api/v2/pokemon/charmander"), | |
notFound: fetcher("https://foo.com/api/not-found"), | |
}); | |
console.log(data); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment