如何在类中与Web Worker一起使用异步javascript代码

时间:2019-02-14 19:22:38

标签: javascript asynchronous web-worker

我写了一个javascript类,实例化后创建了一个web worker。此类中的另一个方法运行worker。我想调用运行工作程序的方法,然后异步地做一些事。为了更好地理解,我在下面添加了原理图代码框架。

我试图在一个类变量中生成并存储Promise,然后对其执行操作,但这似乎是错误的ansatz。 链接到JS Bin

class Task{
  constructor(){
    this.data = 0;
    //this.listen; //my idea, does not work
    this.worker = new Worker('worker.js');

    this.worker.onmessage = (function(e){
      // worker constantly emits messages
      let data = e.data.split(' ');
      // suppose message is now availabe as array
      this.data = data;

      if(data.includes("trigger")){
        //trigger signals that the heavy computation is over

        /* my idea didn't work:
        *this.listen = Promise.resolve(1);
        */
      }
    }).bind(this);
  }

  async doTask(){
    this.worker.postMessage("start computation");
    //wait for the worker to finish calculation
    /*my idea
    *await this.listen;
    */

    //do something after trigger was sent
    return 0;
  }
}

1 个答案:

答案 0 :(得分:2)

也许是这样吗?

class Task{
  constructor(){
    this.data = 0;
    this.worker = new Worker('worker.js');
  }
  async calculation() {
    if (this.worker.onmessage === null) {
      return new Promise(resolve => {
        this.worker.onmessage = e => {
          let data = e.data.split(' ');
          // suppose message is now availabe as array
          this.data = data;

          if(data.includes("trigger")){
            this.worker.onmessage = null;
            resolve();
          }
        };
        this.worker.postMessage("start computation");
      });
    } else {
      console.log('One calc at a time please...');
    }
  }
  async doTask(){
    await this.calculation();

    //do something after trigger was sent
    return 0;
  }
}