Last active
          October 12, 2019 15:57 
        
      - 
      
- 
        Save daniel12fsp/1e8414cfa8f141b92446e5c4ccf82310 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 runWebWorker(func) { | |
| if (typeof func !== "function") { | |
| throw new Error("Argument must be a function"); | |
| } | |
| if (func.name === "") { | |
| throw new Error("Function must have a valid name"); | |
| } | |
| return function (args) { | |
| return new Promise((resolve, reject) => { | |
| const code = ` | |
| self.addEventListener('message', function (e) { | |
| const {funcCode, args} = e.data; | |
| const code ="function func(args) { return (" + funcCode + ")(args)} " | |
| eval(code); | |
| func(args) | |
| .then(self.postMessage) | |
| .catch(self.postMessage) | |
| }, false); | |
| `; | |
| const blob = new Blob([code], {type: 'text/javascript'}); | |
| const url = window.URL.createObjectURL(blob); | |
| const worker = new Worker(url); | |
| worker.postMessage({ | |
| funcCode: func.toString(), | |
| args | |
| }) | |
| worker.addEventListener('message', (e) => { | |
| resolve(e.data) | |
| window.URL.revokeObjectURL(url); | |
| worker.terminate(); | |
| }, false); | |
| }); | |
| } | |
| } | |
| function upperCase(str) { | |
| return new Promise((resolve, reject) => { | |
| resolve(str.toUpperCase()) | |
| }) | |
| } | |
| const upperCaseInWebWorker = runWebWorker(upperCase) | |
| upperCaseInWebWorker("word") | |
| .then((e) => alert("Result from webworker: " + e)) | |
| .catch((e) => alert("Error", e)) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment