Web workers inside promise causing crash

别来无恙 提交于 2019-12-03 22:02:19

The issue is that you are calling makeTile within a nested for loop, where makeTile creates worker. You are creating 950 Worker instances. Each Worker instance calls postMessage. That is the reason the browser is crashing.

You need to adjust you scripts to handle arrays of promises, instead of a single Promise. worker.js should be called once, not 950 times.

You can create an array before the for loops, pass the data as an array to Promise.resolve()

  var arr = [];
  for (let y = 0; y < canvas.height; y += options.tileHeight) {
    for (let x = 0; x < canvas.width; x += options.tileWidth) {
      let areaData = imgContext
                     .getImageData(x, y, options.tileWidth, options.tileHeight);
      arr.push(Promise.resolve([areaData, x, y]))
    }
  };

then after the for loops use Promise.all() to process the data

Promise.all(arr.map(function(tile) {
   this.makeTile(/* tile data here */) // make necessary changes at `makeTile`
   .then(function(tiles) {
     // do stuff with `tiles` array

   })
}))

Move

let worker = new Worker('worker.js');

outside of makeTile(), or create logic so that the call is only made once.

Similarly, at worker.js, adjust the script to handle an array of data, instead of a single value.

When message event is fired at main thread, process the data as an array of values.

The gist of the solution is to refactor your code base to handle arrays, and arrays of promises; both at main thread and at worker.js; with the object being to call worker.js at most once at change event of <input type="file"> element. Where a single message is posted to Worker, and single message event is expected from Worker. Then do stuff with the returned array containing the processed data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!