如何使用async/await将此回调转换为承诺?

ddarikpa  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(348)

以下函数从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 因为函数正在运行,但映像尚未加载。
仅当照片已加载且宽度和高度已可用时,如何使用wait/async返回值?

csga3l58

csga3l581#

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

raogr8fs2#

此库工作得非常好-它允许连接到子进程,或者如果需要,只需异步返回结果:https://github.com/expo/spawn-async

相关问题