I have this function that converts an image URL to a base64 image string. The thing is that the function needs a callback, and I use a console.log to print the string (which works), but I need the string to be saved in a variable. Here is the code:
function convertImageToBase64(imgUrl, callback) {
const image = new Image();
image.crossOrigin = 'anonymous';
image.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.height = image.naturalHeight;
canvas.width = image.naturalWidth;
ctx.drawImage(image, 0, 0);
const dataUrl = canvas.toDataURL();
callback && callback(dataUrl);
}
image.src = imgUrl;
}
And here’s how I call the function:
convertImageToBase64(imgEmpresa, console.log);
convertImageToBase64(imgPropia, console.log);
Both img variables are URL strings I obtain through other methods.
It works perfectly fine, and the output of the console.log is the base64 string. But the thing is that I need that variable to be stored somewhere and I have literally no clue on how to do it.
I tried making a function to serve as callback that just returns the variable, but that doesn’t work
4
Answers
There is no return in your function. You need to return that value.
You need to "promisify" it:
and then
await convertImageToBase64(...)
somewhere else.See also How do I return the response from an asynchronous call?
I can think of two ways. 1) You return the value from the function and store the value outside. Or you do it already in the function.
or
Assuming you can not change the original function: Use a closure to store the value, or pass the function that needs to consume it later on.