Last active
October 25, 2018 07:54
-
-
Save joshuacerbito/ccef42b64485795b2ec5e420ad476924 to your computer and use it in GitHub Desktop.
Web Worker for a generic 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
/* | |
* Fetch Worker | |
* Usage: | |
* const fetchWorker = new Worker('./fetch-worker.js'); | |
* fetchWorker.postMessage('https://some.api/with-data.json'); | |
*/ | |
self.addEventListener(‘message’, e => { | |
let url = e.data; | |
fetch(url).then(res => { | |
if (res.ok) { | |
self.postMessage(res); | |
} else { | |
throw new Error(’Fetch encountered an error with the server.’); | |
} | |
}).catch(err => { | |
self.postMessage(err.message); | |
}); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment