1

I have written a promise based loading image function.

function loadImage() {
    const img = new Image();


    return new Promise((resolve, reject) => {
      img.addEventListener("load", () => {
        resolve();
      });

      img.addEventListener("error", () => {
        reject();
      });

      img.src = 'assets/myImg.jpg';
    });
}

loadImage.then(
  () => console.log('image loaded'),
  () => console.error('image did not load')
);

I would like to convert it using the async/await but I am actually struggling to do it. Any idea how it can achieved ?

Scipion
  • 11,449
  • 19
  • 74
  • 139

2 Answers2

1

You can await your loadImage function, but the new Image() object doesn't use promises, it uses events which you've wrapped with a Promise.

Inside of an async function, you can await your loadImage function, like so:

async function loadImage() {
    const img = new Image();

    return new Promise((resolve, reject) => {
      img.addEventListener("load", () => {
        resolve();
      });

      img.addEventListener("error", () => {
        reject();
      });

      img.src = 'assets/myImg.jpg';
    });
}

async function doSomething() {
  try {
    await loadImage();
    console.log("image loaded");
  } catch(e) {
    console.error("image did not load");
  }
}

steadweb
  • 15,364
  • 3
  • 33
  • 47
0

With a couple changes you can make it work. The async await side of things would generally replace the ".then()" chaining.

First of all, keep the loadImage() function as is, and define an additional "async" function to run your async await code in. I've called this "main()". You can then create a variable, for example "loadedImage", and then await the promise function. This will pause execution of the next step (being the console log in this case) until the promise has resolved/rejected and the image is loaded.

async function main() {
    let loadedImage = await loadImage();
    console.log(loadedImage);
}

main()

Additionally, if you wanted to actually return a value into the loadedImage variable (as right now it will be undefined), inside your promise "resolve()" you can place a value. Eg:

resolve('the image has loaded')

Justin Feakes
  • 380
  • 1
  • 7