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

How to use async/await to turn this callback function into a 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;
  });
}

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

You can do

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

Leave a Comment