Assuming this is somewhere inside a function, you can make it async and use await to wait for the Promise to complete once you return it from the blob2uint function:
async function myBlobToUIntDemo() {
let str='content';
str2blob=(str,type='text/plain')=>new Blob([str],{type:type});
let blob=str2blob(str);
function blob2uint(blob){
return new Response(blob).arrayBuffer().then(buffer=>{
uint=[...new Uint8Array(buffer)];
console.log("Uint8Array",uint);
return uint;
});
}
let uint8data = await blob2uint(blob);
console.log(uint8data); //Show Uint8Array
}
Let's spike this up with some more information:
Why do I need a callback in the first place?
Because you are doing asynchronous work by pulling the arrayBuffer from a response. JavaScript (as far as I know) only runs in a single thread. Waiting for a website in your code without using a callback would halt all other JavaScript execution on your page if you didn't put it in the background somehow; that's what callbacks and Promises do for you (from the outside at least).
Promises?
Functions doing asynchronous work typically return a Promise
object, that promises to provide you with the value once the work completes (by calling the function passed in the then
callback with it) or an error in case something goes wrong (by calling the catch
callback with it).
async / await
async / await was introduced to make working with Promises a bit nicer and readable, reducing the need for callbacks a lot. You can read more about that in this MDN article.
The code block above only contains the bare minimum changes to get things working. Let's simplify that a bit more!
async function myBlobToUIntDemo() {
let str = 'content';
let str2blob = (str, type = 'text/plain') => new Blob([str], { type: type });
let blob = str2blob(str);
const buffer = await new Response(blob).arrayBuffer();
const uint = [...new Uint8Array(buffer)];
console.log(uint);
}
Note that this returns a Promise as well (this automatically happens if you mark your function as async) so make sure to remember that if you were to use this function anywhere in your code.