Created
November 23, 2022 15:35
-
-
Save markknol/6ce8cba8917b0b8860535cd2ba5fe29c to your computer and use it in GitHub Desktop.
parsing json in a worker
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
// promisified version of parsing json in a worker | |
// usage: `let data = await fetch(url).then(v => v.text()).then(v => parseJson(v)).then(data => console.log(data));` | |
function parseJson(txt:string) { | |
return new Promise((resolve, reject) => { | |
var blob = new Blob([ | |
'this.onmessage = function(message) {\n' + | |
'postMessage(JSON.parse(message.data));\n' + | |
'};' | |
], { type: "text/javascript" }); | |
var w = new Worker(URL.createObjectURL(blob)); | |
w.onmessage = (message) => resolve(message.data); | |
w.postMessage(txt); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment