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.
For async loading to work, either load it in JavaScript and use the onload, or include the image tag on the page, without the src attribute (specify the width and height in HTML), and go back at some point, in JS, and set the image URL.
A view that asynchronously loads and displays an image.
async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
Your problem here extends from the definition for await
...
The
await
operator is used to wait for aPromise
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)) }
Previous answers are correct, but I wanted to point out that there is now an HTMLImageElement.decode()
method which almost corresponds to a Promisified onload handler.
This has the advantages of not needing to do the wrapping yourself, to handle already loaded images (previous answers fail this case), and to wait for the image to be actually decoded, which may be a good thing in various situation (e.g if you wanted to use it with the synchronous Canvas2DContext.drawImage()
method, your script would get blocked while this decoding is done).
So now all it takes is
(async () => { const img = new Image(); img.src = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"; await img.decode(); // img is ready to use console.log( `width: ${ img.width }, height: ${ img.height }` ); })();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With