0

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?

2
  • 1
    What is the purpose of trying to turn an image into a string? Commented Mar 7, 2021 at 23:06
  • This function doesn't make any sense. Either image is a DOMString, and you get back the exact same output as the input, either it's some binary data (from an ArrayBuffer) and here, either it represents an UTF8 text, in which case a TextDecoder is far preferable to do the same, either it's some other data in which case you'll break it by reading it as UTF8. So the only usecase would be if image was a Blob representing an UTF8 encoded text file, but in that case, no need to wrap it into a new Blob. Commented Mar 7, 2021 at 23:37

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, thanks. I think I should learn more about JS magic like this.
@Punk1503 - This isn't really magic at all. This is just using a promise how a promise is designed. You should also note that apply_blob() will return BEFORE element.value is assigned its new value and the caller of apply_blob() in this interface has no way of knowing when this is done (which is sometimes an API design problem). That assignment will happen at some indeterminate time later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.