Async waits while loading image

Temp.js

export default class Temp {
    async addImageProcess(src){
        let img = new Image();
        img.src = src;
        return img.onload = await function(){
          return this.height;
        }
    }
}

anotherfile.js

import Temp from '../../classes/Temp'
let tmp = new Temp()

imageUrl ="https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png"
let image = tmp.addImageProcess(imageUrl);
console.log(image)

Above is my code. I have an image url and trying to get image properties using async, but it doesnโ€™t work, I donโ€™t understand what I missed.

+4
source share
1 answer

Your problem here stems from the definition forawait ...

The operator is awaitused to wait.Promise

A property is Image.prototype.onloadnot a promise, and you do not assign it. If you want to return the property heightafter loading, instead I will create Promise...

addImageProcess(src){
  return new Promise((resolve, reject) => {
    let img = new Image()
    img.onload = () => resolve(img.height)
    img.onerror = reject
    img.src = src
  })
}

Then you used the following to access this value

tmp.addImageProcess(imageUrl).then(height => {
  console.log(height)
})

or if inside a function async

async function logImageHeight(imageUrl) {
  console.log('height', await tmp.addImageProcess(imageUrl))
}
+8
source

Source: https://habr.com/ru/post/1686323/


All Articles