async await in image loading
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 }` );
})();