【问题标题】:How to turn this callback into a promise using async/await?如何使用 async/await 将此回调转换为 Promise?
【发布时间】: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


    【解决方案1】:

    如何使用async/await把这个回调函数变成一个promise?

    你没有。 As usual, you use the new Promise constructor。没有语法糖。

    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))
    }
    

    【讨论】:

      【解决方案2】:

      这个库工作得很好——它允许连接到子进程或在需要时简单地异步返回结果:https://github.com/expo/spawn-async

      【讨论】:

        猜你喜欢
        • 2018-12-12
        • 2019-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-14
        • 1970-01-01
        相关资源
        最近更新 更多