JS get string from blob

I have a function

async function create_blob(image) {
    const blob = new Blob([image])
    return await blob.text()
}

And I want it to return a string. When I try to use this data blob_hidden_input.value = create_blob(file_object) blob_hidden_value.value is “[Promise object]”. So how to convert promise to string without black magic?

Answer

Well, you kinda have to do some black magic to make it work. But hey, black magic is fun sometimes.

function apply_blob(element, image) {
   (new Blob([image]).text().then(value => element.value = value);
}

Just pass in the blob_hidden_input as the element parameter.

Because its a promise, there is no way for you to get the value of the promise at the moment the promise is returned unless the promised action is synchronous, which the blob isn’t.

This function will apply the value in a way that appears to be instantly, but it is actually slightly delayed. This is how promises work, and you can’t get around it sadly.

Leave a Reply

Your email address will not be published. Required fields are marked *