Monday, May 20, 2024
148
rated 0 times [  155] [ 7]  / answers: 1 / hits: 77988  / 7 Years ago, mon, september 25, 2017, 12:00:00

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 a image url and tried to get image's properties using async await but it's not working, don't understand what I missed.


More From » ecmascript-6

 Answers
47

Your problem here extends from the definition for await...



The await operator is used to wait for a Promise



The Image.prototype.onload property is not a promise, nor are you assigning it one. If you're wanting to return the height property after loading, I would instead create a Promise...


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

You would then use the following to access that value


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

or, if within an async function


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

[#56397] Thursday, September 21, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nestorjarettg

Total Points: 451
Total Questions: 108
Total Answers: 108

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;