Last active
November 7, 2019 05:19
-
-
Save DSchau/10122afd2a3713108b9ed2f40991bb74 to your computer and use it in GitHub Desktop.
Semi Resilient Network Request
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
// make sure you wrap this in a useEffect, componentDidMount, etc. | |
const safeFetch = (timeout = 10000) => { | |
return (...args) => { | |
// this is sorta "unsafe" in the sense that a slow connection could cause this timeout | |
// a safer way would be to tap into and investigate error codes for e.g. ad blocked resources | |
// but this gets the idea across | |
return Promise.race([ | |
fetch(...args), | |
new Promise((resolve, reject) => setTimeout(() => reject(new Error('Ad blocked or something')), timeout) // this failed, short-circuit | |
]) | |
} | |
} | |
safeFetch()('/whatever.json') // if blocked, will reject after 10 seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment