Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readAsDataURL async/await [duplicate]

I'm trying to resize a file which I get from Quill and send it to a server. This is what I have

async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
  // Resizing
  var newFile
  const reader = new FileReader();
  reader.onload = function (e) {
      var img = document.createElement("img");
      img.onload = function (event) {
        // Dynamically create a canvas element
        var canvas = document.createElement("canvas");
        
        // var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");

        // Actual resizing
        ctx.drawImage(img, 0, 0, 300, 300);

        // Show resized image in preview element
        canvas.toBlob(blob => {
          newFile = blob; 
          console.log(newFile)                           
        });
      }
      img.src = e.target.result;
    }
  reader.readAsDataURL(file);

  console.log(newFile)
  //Sending data to server 
}      

I want to make this code work in an 'async/await' way, so the second console.log(newFile) would also return a correct value, unfortunately, I don't get how to update the code.

Any help is massively appreciated :-)

like image 324
Pavel Shepelenko Avatar asked May 09 '26 23:05

Pavel Shepelenko


1 Answers

You need to put it inside a promise.

    var newFile

    const reader = new FileReader();

    const promise = new Promise(resolve => {
            reader.onload = function (e) {
                var img = document.createElement("img");
                img.onload = function (event) {
                    // Dynamically create a canvas element
                    var canvas = document.createElement("canvas");
                    
                    // var canvas = document.getElementById("canvas");
                    var ctx = canvas.getContext("2d");

                    // Actual resizing
                    ctx.drawImage(img, 0, 0, 300, 300);

                    // Show resized image in preview element
                    canvas.toBlob(blob => {
                        newFile = blob; 
                        console.log(newFile) 
                        resolve();
                    });
                    
                }
                img.src = e.target.result;
            }
    });

    reader.readAsDataURL(file);

    await promise;

    console.log(newFile)
like image 77
Achshar Avatar answered May 11 '26 12:05

Achshar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!