【发布时间】:2017-08-21 03:29:21
【问题描述】:
以下函数从 url 获取图像,加载它,并返回它的宽度和高度:
function getImageData (url) {
const img = new Image()
img.addEventListener('load', function () {
return { width: this.naturalWidth, height: this.naturalHeight }
})
img.src = url
}
问题是,如果我这样做:
ready () {
console.log(getImageData(this.url))
}
我得到undefined,因为函数运行但图像尚未加载。
如何使用await/async在图片加载完毕且宽高已经可用的情况下才返回值?
【问题讨论】:
标签: javascript asynchronous promise async-await