The following function takes and image from an url, loads it, and returns its width and height:
function getImageData (url) {
const img = new Image()
img.addEventListener('load', function () {
return { width: this.naturalWidth, height: this.naturalHeight }
})
img.src = url
}
The problem is, if I do something like this:
ready () {
console.log(getImageData(this.url))
}
I get undefined
because the function runs but the imaged hasn't loaded yet.
How to use await/async to return the value only when the photo has loaded and the width and height is already available?
You don't. As usual, you use the
new Promise
constructor. There's no syntactic sugar for that.You can do
This library works pretty well - it allows connection to the child process or simply returns the result asynchronously if desired: https://github.com/expo/spawn-async