-1

Hello I have this function:

  const getImageSize = (url) => {
    const img = new Image()
    img.src = url
    return img.onload = async function() {
      
      return{
        height: this.height,
        width: this.width,
        scale: parseInt(this.height / this.width)
      }
    }
    
  }

and I call it like this

  const test = async () =>{
    const imageSize = await getImageSize(data[0].image.url)
    console.log(imageSize)
  }

I get the function itself but not the values. How can I solve this?

This is the log:

ƒ () {
    var self = this,
        args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);

      function _next(value) {
        asyncGeneratorStep…
otto
  • 1,815
  • 7
  • 37
  • 63
  • You need to use an explicit promise (`new Promise`) and not the `async` keyword to solve this problem. – Quentin Sep 22 '20 at 16:44

1 Answers1

1

async is just syntax sugar of Promise. For this case you can just return a promise like:

  const getImageSize = (url) => {
    const img = new Image()
    img.src = url
    let resolve
    img.onload = function() {
      resolve({
        height: this.height,
        width: this.width,
        scale: parseInt(this.height / this.width)
      })
    }

    return new Promise(r => resolve = r)
  }
hackape
  • 18,643
  • 2
  • 29
  • 57