如何使用async/await将此回调函数转换为promise?

8
以下函数接受来自 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,在图片加载完成并且宽度和高度已经可用时才返回值?

2个回答

33

如何使用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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接