如何使用async / await将此回调转换为承诺? [英] How to turn this callback into a promise using async/await?

查看:183
本文介绍了如何使用async / await将此回调转换为承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下函数从网址获取图片,加载并返回其宽度和高度:

The following function takes and image from an url, loads it, and returns its width and height:

function getImageData (url) {
  const img = new Image()
  img.addEventListener('load', function () {
    return { width: this.naturalWidth, height: this.naturalHeight }
  })
  img.src = url
}

问题是,如果我做这样的事情:

The problem is, if I do something like this:

ready () {
  console.log(getImageData(this.url))
}

我得到 undefined 因为函数运行但imaged尚未加载。

I get undefined because the function runs but the imaged hasn't loaded yet.

如何使用await / async仅在照片加载时返回值以及宽度和高度已经可用?

How to use await/async to return the value only when the photo has loaded and the width and height is already available?

推荐答案


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

How to use async/await to turn this callback function into a promise?

你没有。 像往常一样,您使用新Promise 构造函数。这没有语法糖。

You don't. As usual, you use the new Promise constructor. There's no syntactic sugar for that.

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




如何使用等待 / async 仅在照片已加载并且宽度和高度已经可用时记录该值?

How to use await/async to log the value only when the photo has loaded and the width and height is already available?

你可以做

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

这篇关于如何使用async / await将此回调转换为承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆