Created
January 27, 2021 16:23
-
-
Save barklund/1b5a9f9ee1b68d65027fb0c912e88f14 to your computer and use it in GitHub Desktop.
Return best weather service that answers within a timed limit
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
function fetchWeather(services, timeout) { | |
let bestData = null; | |
const controllers = services.map(() => new AbortController()); | |
const cancelFrom = index => controllers.slice(index).map(c => c.abort()); | |
const fetches = services.map((url, index) => | |
fetch(url, {signal: controller[index].signal}) | |
.then((res) => { | |
bestData = res; | |
cancelFrom(index+1); | |
return res; | |
}) | |
); | |
const limit = new Promise(r => setTimeout(r, timeout)) | |
.then(() => cancelFrom(0)); | |
return Promise.race([limit, fetches[0]]) | |
.then(() => bestData) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could solve it by adding a catch handler to line 6 returning the next promise in the chain - a bit ugly, but it might work!