0

I have this JavaScript code that works perfectly for me to convert the URL of an image to BASE64, but I have not been able to return the result in JSON or string format, when I return it appears [object Promise]

If anyone knows what I'm doing wrong, I'd appreciate your help

const getImg64 = async() => {
  const convertImgToBase64URL = (url) => {
    console.log(url)
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.crossOrigin = 'Anonymous';
      img.onload = () => {
        let canvas = document.createElement('CANVAS')
        const ctx = canvas.getContext('2d')
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        const dataURL = canvas.toDataURL();
        canvas = null;
        resolve(dataURL)
      }
      img.src = url;
    })
  }
  //for the demonstration purposes I used proxy server to avoid cross origin error

  const image = await convertImgToBase64URL('https://image.shutterstock.com/image-vector/vector-line-icon-hello-wave-260nw-1521867944.jpg')
  console.log(image)

}



getImg64()

const return_data = getImg64().toString()
console.log(return_data)
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
joyanader
  • 35
  • 6
  • Why are you using a `Promise`? You can remove it, everything within it is synchronous. – bryce Jun 29 '22 at 20:00
  • @bryce `img.onload` is not synchronous? – Bergi Jun 29 '22 at 20:04
  • I don't see the problem, your code works and logs the desired value. Sure, `getImg64()` returns a promise, but it can't do anything other than that, the image needs to load first so it cannot immediately return a string. – Bergi Jun 29 '22 at 20:07
  • Thank you very much, what should I do to be able to take the result of that promise to a json or a string? i'm stuck on that part – joyanader Jun 29 '22 at 20:08
  • I edited your snippet to show the actual problem, which is that you are calling `toString()` on the result of `getImg64()`, which is a promise. Instead, as with all async code, you need to write your string within the asynchronous context. So if you're going to be sending this in JSON via `fetch`, you'd need to do the `fetch` within `getImg64()` or within an async function that awaits `getImg64()`. – Heretic Monkey Jun 29 '22 at 20:11
  • thanks ! @HereticMonkey I'm reading what you sent me – joyanader Jun 29 '22 at 22:54

0 Answers0