Search code examples
javascriptasynchronousblobarraybuffertyped-arrays

Javascript Async buffer copy


So I know this might be a long-shot, but perhaps someone could help.

Is there any way I could copy a buffer asynchronously? Possibly by using a blob somehow? Below is an example of something kinda along the lines of what I'm looking for (obviously doesn't work, just to illustrate). Need this to work client side.

var fromBuffer = new Uint8Array(1056); //just some random data
var bufferToCopyTo;
var req = new XMLHttpRequest();
req.open("GET", "fromBuffer", true);
req.responseType = "blob";

req.onload = function(e) {
  bufferToCopyTo = req.response;

};

req.send();
//continue while buffer makes a copy in the background?

Solution

  • Is there any way I could copy a buffer asynchronously?

    No, a buffer cannot be copied while other code is running as otherwise there might a race condition to access/write elements of the buffer.

    What you can however do, if the copying is taking an abnormal amount of time and chunking doesn't help, is to transfer the buffer to a background worker, make a copy of it in there, and transfer both back to the main thread. This of course means that the buffer cannot be used while it is being copied.