I'm creating a blob
from a canvas
and can only return an undefined variable with the following:
function resample(canvas, width, height) {
var resizer = sizeo();
var datablob;
var canvasResampled = document.createElement('canvas');
canvasResampled.width = width;
canvasResampled.height = height;
resizer.resize(canvas, canvasResampled)
.then(result => resizer.toBlob(result, 'image/jpeg', 75))
.then(blob => datablob = blob);
console.log(datablob);
return datablob;
}
As mentioned, the console
shows undefined. If I run a console.log
in the format of:
then(blob => console.log(blob));
instead of trying set the datablob
variable, I get told there's an image/jpeg
there, which is what I'm intending. I'm fresh-faced to es6 and fat arrows so I've likely overlooked something.
Edit:
If the value is undefined because promises are asynchronous, how can I perform the same task? As in, how do I return datablob
with a ready value? I can't return from within the then
statements, obviously, but I'm unsure about how to unsure the return value of the function waits.
As I see it now, if it involves creating some separate callback, is my use of then
and fat arrow not as convenient for this situation as I blindly walked into? I was finding it quite convenient to tell javascript that when x is ready, do the following with x and it only feels natural that I can end with when z is ready, return z as the return value of the function but it looks like this last request is not as elegant to pull off as the previous statements?