Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn this callback into a promise using 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))
}

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

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

like image 558
alex Avatar asked Aug 21 '17 03:08

alex


People also ask

How do I change my callback to promise?

If the callback function returns non-error output, we resolve the Promise with the output. Let's start by converting a callback to a promise for a function that accepts a fixed number of parameters: const fs = require('fs'); const readFile = (fileName, encoding) => { return new Promise((resolve, reject) => { fs.

What is callback promise async await?

Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.

How do I use async await with promises?

async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

Can a callback function be async?

The function that takes another function as an argument is called a higher-order function. According to this definition, any function can become a callback function if it is passed as an argument. Callbacks are not asynchronous by nature, but can be used for asynchronous purposes.


1 Answers

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))
}
like image 189
Bergi Avatar answered Nov 15 '22 18:11

Bergi