web workers中的onmessage无法访问类变量

huangapple go评论64阅读模式
英文:

onmessage in web workers can not access class variable

问题

I am making multithreading file uploading .

when I access to Class variable in myWorker.onmessage, it shows error.

app.4c7f2a2a.js:32 Uncaught TypeError: Cannot read properties of undefined (reading 'length')
    at a.onmessage 

How can I solve this error ?

check my source code.

// queue.js
class Queue {
    constructor() {
        this.items = [];
        this.size = -1;
    }
    sendChunk(chunkId) {
        if (window.Worker) {
            const myWorker = new Worker("/worker.js");
            myWorker.postMessage([chunkId]);
            myWorker.onmessage = function (e) {
                console.log(e.data);
                console.log(this.size); // <-- this make error
            }
        }
    }
}
export default Queue;
// worker.js
onmessage = async function (e) {
    const count = e.data[0];
    const data = {
        count: count,
        local_time: new Date().toLocaleTimeString(),
    };

    fetch('/time', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        })
        .then((response) => {
            return response.json();
        })
        .then((data) => {
            postMessage(JSON.stringify(data));
        })
        .catch((error) => {
            console.error('Error:', error);
        });
}
// main.js
import Queue from './queue';
const q = new Queue();
q.startQueue();

console.log(this.size); makes error.

英文:

I am making multithreading file uploading .

when I access to Class variable in myWorker.onmessage, it shows error.

app.4c7f2a2a.js:32 Uncaught TypeError: Cannot read properties of undefined (reading &#39;length&#39;)
    at a.onmessage 

How can I solve this error ?

check my source code.

// queue.js
class Queue {
    constructor() {
        this.items = [];
        this.size = -1;
    }
    sendChunk( chunkId) {
        if (window.Worker) {
            const myWorker = new Worker(&quot;/worker.js&quot;);
            myWorker.postMessage([chunkId]);
            myWorker.onmessage = function (e) {
                console.log(e.data);
                console.log(this.size); // &lt;-- this make error
            }
        }
    }
}
export default Queue;
// worker.js
onmessage = async function (e) {
    const count = e.data[0];
    const data = {
        count: count,
        local_time: new Date().toLocaleTimeString(),
    };

    fetch(&#39;/time&#39;, {
            method: &#39;POST&#39;,
            headers: {
                &#39;Content-Type&#39;: &#39;application/json&#39;,
            },
            body: JSON.stringify(data),
        })
        .then((response) =&gt; {
            return response.json();
        })
        .then((data) =&gt; {
            postMessage(JSON.stringify(data));
        })
        .catch((error) =&gt; {
            console.error(&#39;Error:&#39;, error);
        });
}
// main.js
import Queue from &#39;./queue&#39;;
const q = new Queue();
q.startQueue();

console.log(this.size); makes error.

答案1

得分: 1

`this`将在`onmessage`函数的范围内。如果你需要在`onmessage`回调中使用类变量,可以像下面的例子中那样将`this`存储到其他变量(如`that`),然后访问其中的成员。

// queue.js
class Queue {
constructor() {
this.items = [];
this.size = -1;
}
sendChunk(chunkId) {
if (window.Worker) {
const myWorker = new Worker("/worker.js");
myWorker.postMessage([chunkId]);
const that = this;
myWorker.onmessage = function (e) {
console.log(e.data);
console.log(that.size);
}
}
}
}
export default Queue;


<details>
<summary>英文:</summary>

`this` will be within the scope of the `onmessage` function. If you need to use the class variables within the callback of `onmessage` then, you can store `this` into some other variable like `that` in the example below and then access the members within.

// queue.js
class Queue {
constructor() {
this.items = [];
this.size = -1;
}
sendChunk( chunkId) {
if (window.Worker) {
const myWorker = new Worker("/worker.js");
myWorker.postMessage([chunkId]);
const that = this
myWorker.onmessage = function (e) {
console.log(e.data);
console.log(that.size);
}
}
}
}
export default Queue;


</details>



huangapple
  • 本文由 发表于 2023年2月18日 13:29:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75491400.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定