简体   繁体   中英

How to send transferrable object from web worker to parent in javascript?

In JS, I made a web worker, and want to send a transferable object back to parent.

In the web worker, I have

var NUMS = new ArrayBuffer(3);
NUMS[0] = 10;
NUMS[1] = 11;
NUMS[2] = 12;
postMessage(NUMS, [NUMS]);

Then in the main thread, I have

worker.onmessage = function(e) {
    var first = e.data[0]; // undefined but the bytelength is 3
}

but what happens is all the values of the array buffer seems to be cleared or invalid. Does anyone know how to fix this?

Turns out you need to use one of the typed arrays

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays

var NUMS = new Int16Array(3);
NUMS[0] = 10;
NUMS[1] = 11;
NUMS[2] = 12;
postMessage(NUMS.buffer, [NUMS.buffer]);

then you can get it by

worker.onmessage = function(e) {
    var a = new Int16Array(e.data);
    var first = a[0]; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM