Created
July 13, 2018 08:28
-
-
Save Akiyamka/650951b53765a61d1273c2ccfe4dbccf to your computer and use it in GitHub Desktop.
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
| function toBlob(func) { | |
| const funcString = func.toString(); | |
| const code = funcString.substring( | |
| funcString.indexOf('{') + 1, | |
| funcString.lastIndexOf('}'), | |
| ); | |
| const blob = new Blob([code], { type: 'application/javascript' }); | |
| return URL.createObjectURL(blob); | |
| } | |
| function workerFunc() { | |
| /* eslint-disable no-restricted-globals */ | |
| /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "$" }] */ | |
| function $createRequest({ url, body, method = 'POST' }) { | |
| const data = { | |
| method, | |
| mode: 'cors', | |
| cache: 'default', | |
| credentials: 'include', | |
| body: JSON.stringify(body), | |
| }; | |
| return fetch(new Request(`https://beta.api.adx1.com/v1.0.2/${url}`, data)).then( | |
| res => | |
| res.text().then(text => { | |
| if (res.ok || res.status === 400) { | |
| return text; | |
| } | |
| throw new Error(res.status, res); | |
| }), | |
| ); | |
| } | |
| self.onmessage = e => { | |
| const { tasks, $models } = JSON.parse(e.data); | |
| function deSerialazedFunc(string) { | |
| try { | |
| /* eslint-disable-next-line no-eval */ | |
| return eval(`(${string})`); | |
| } catch (error) { | |
| console.error(error); | |
| return null; | |
| } | |
| } | |
| const requests = tasks.map(fstr => deSerialazedFunc(fstr)); | |
| requests | |
| .reduce( | |
| (prevPromicse, task) => | |
| prevPromicse.then(previosResponse => { | |
| if (typeof task === 'function') { | |
| return task(previosResponse); | |
| } | |
| return Promise.resolve(previosResponse); | |
| }), | |
| Promise.resolve(null), | |
| ) | |
| .then(lastResponse => { | |
| self.postMessage(lastResponse); | |
| }); | |
| }; | |
| /* eslint-enable no-restricted-globals */ | |
| } | |
| export function createWorker(models, tasks, callBack) { | |
| const worker = new Worker(toBlob(workerFunc)); | |
| const tasksAsStrings = tasks.map(f => f.toString()); | |
| worker.postMessage(JSON.stringify({ tasks: tasksAsStrings, $models: models })); | |
| worker.onmessage = e => { | |
| callBack(e); | |
| }; | |
| return Promise.resolve(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment