以下函数从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因为该函数运行了,但是图像尚未加载。仅当照片已加载且宽度和高度已可用时,如何使用等待/异步返回值?
2 回答

呼啦一阵风
TA贡献1802条经验 获得超6个赞
如何使用async/ await将此回调函数转换为Promise?
你不知道 与往常一样,您可以使用new Promise构造函数。没有语法糖。
function loadImage(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener('load', () => resolve(img));
img.addEventListener('error', reject); // don't forget this one
img.src = url;
});
}
仅当照片已加载且宽度和高度已经可用时,如何使用await/ async记录值?
你可以做
async function getImageData(url) {
const img = await loadImage(url);
return { width: img.naturalWidth, height: img.naturalHeight };
}
async function ready() {
console.log(await getImageData(this.url))
}
添加回答
举报
0/150
提交
取消