0

embedFromString: function(url, mediaType) {
  let img = new Image,
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d"),
    src = url;
  let imgBase64;
  img.crossOrigin = "Anonymous";
  img.src = src;
  return new Promise(((resolve, reject) => {

    img.onload = async function() {

      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0);
      imgBase64 = canvas.toDataURL("image/png");
      console.log(imgBase64, 'hello');
      this.mediaType = mediaType;
      this.url = imgBase64.split(',')[1];
      this.base64 = true;

      return resolve();
    }
  }));
}

In this function, this.mediaType / this.url/ this.base64 are not updated with new values. Even though updated values are in mediaType / imgBase64 / base64 respectively. How to set these updated value with "this"

DecPK
  • 24,537
  • 6
  • 26
  • 42
Parul
  • 31
  • 5
  • 1
    The `async` for the `onload` event handler is useless. – Andreas Sep 28 '21 at 12:43
  • 2
    It isn't anything to do with promises. Your `img.onload` callback is a traditional function, so `this` will be the element. Make it an arrow function isntead. Also, there's no reason for it to be an `async` function, you're not using `await` anywhere inside it. – T.J. Crowder Sep 28 '21 at 12:44
  • Slightly tangential, but when writing a function like `embedFromString`, it's generally best to put **all** the code inside the promise executor function (the callback you pass `new Promise`), rather than only some of it. That's because you want the function to reliably use the promise to signal completion. If some of the code is at the top level of the function before you call `new Promise`, and an error occurs in that code, the function will throw an error rather than returning a promise. If the code is in the promise executor function, it will reject the promise instead. – T.J. Crowder Sep 28 '21 at 12:46
  • 1
    @Andreas - The reflected property is [`crossOrigin`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/crossOrigin) (capital `O`), even though the attribute is all lower-case. You're right that the value should be `"anonymous"` in all lower case. – T.J. Crowder Sep 28 '21 at 12:47
  • `return new Promise` and `resolve()` are equally usless. You are simply defining a function that executes on load. There's no need to return a Promise or even resolve it. For that matter, it resolves with no value. – Jeremy Thille Sep 28 '21 at 12:48
  • @JeremyThille - The code does asynchronous work (it waits for the image to load before doing its processing), so to me it makes sense to return a promise. It's okay not to have a fulfillment value, if all you want to know is that the operation finished (or failed). But it really depends on more context. I too tend to prefer meaningful fulfillment values. (I'm not saying this is how I would write this code! :-D ) – T.J. Crowder Sep 28 '21 at 12:50

0 Answers0