下面的函数从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只在照片已经加载并且宽度和高度已经可用的情况下返回值?
如何使用async
/await
将这个回调函数变成一个承诺?
你不知道。与往常一样,您使用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))
}
这个库工作得非常好--它允许连接到子进程,或者只需异步返回结果(如果需要的话):https://github.com/expo/spawn-async