0

I have a class which contains a function, so I want to be able to call a class method inside the function

I want to find a way to access the class method send and the attribute file inside the worker_fn function ?

class Upload {
  * uploadFiles(files: FileList | File[]) {
    let file;
    for (let i = 0; i < files.length; i++) {
      if (filesAdded === 1) {
        break;
      }
      file = files[i];
      if (this.types.indexOf(file.type) > -1) {
        filesAdded++;
      } else {
        this._showBadExtensionError();
        return false;
      }
    }
    var worker_fn = () => {
      this.send(file); // i want to able to access send() method and file attribute above 
      self.postMessage('upload sucessfully...');
    };
    var blob = new Blob(["onmessage =" + worker_fn.toString()], {
      type: "text/javascript"
    });

    var worker = new Worker(window.URL.createObjectURL(blob));

  }
  send(file: File, url) {
    let formData = new FormData();
    formData.append('file', file, file.name);
    const response = await this.apiRequest.POST(url, formData);
    return response.json();
  }

}
bartocc
  • 727
  • 1
  • 7
  • 19
  • 2
    The Worker runs in an isolated context from your main script - you can't directly pass functions, Files, etc.. to it - you can only communicate with it via messages, see [Using WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Transferring_data_to_and_from_workers_further_details) – Turtlefight Sep 10 '19 at 09:27
  • WTH is `uploadFiles` a generator method? – Bergi Sep 10 '19 at 18:09

0 Answers0