4

I have a weird one I can't wrap my brains around.

const load = url => {
  return new Promise( resolve => {
    const img = new Image()
    img.onload = () => resolve({ url, ratio: img.naturalWidth / img.naturalHeight })
    img.src = url
  })
}

How am I supposed to use async / await given the onload is just a callback assignment ... I am stuck at the following:

const load = async url => {

    const img = new Image()
    img.src = url
    return await img.onload = () => ({ url, ratio: img.naturalWidth / img.naturalHeight })

    // cannot use await for img.onload obviously ..
    // nor can I put await in the onload function ... since it's not going to do anything

}

Is it possible to solve without having to use the resolve method ?

Eduard
  • 3,395
  • 8
  • 37
  • 62
  • uhm. the first example looks appropriate. the second looks... wrong. The first example can be awaited in an async function. the second example seems to be misunderstanding what async/wait is. – Kevin B Mar 26 '18 at 18:34
  • 3
    async/await doesn't replace promises, it just allows you to consume them in a different way. – Kevin B Mar 26 '18 at 18:36
  • Yea, sorry for misleading you, I know how to use them, it's just that I cannot figure out how to use async / await in this given case, to replace the Promise / resolve ( callback syntax ). Was just wondering if someone with more brains can figure this out without the use of them – Eduard Mar 26 '18 at 18:38
  • 1
    you can't though. You can't take something that doesn't return a promise and await it, it has to be already returning a promise. async/await doesn't help in that scenario. – Kevin B Mar 26 '18 at 18:38
  • Makes sense now that I think of it.. was wondering though if someone else knows or has a way to make that load into a promise easier. Thanks for the clarification – Eduard Mar 26 '18 at 18:40
  • You can't make it easier, *it's fine*. That's why i answered as i did. – H.B. Mar 26 '18 at 18:43

1 Answers1

3

I do not get what you are trying to do there in the second bit of code, but the upper one works just fine and can be used like this:

const load = url => new Promise( resolve => {
    const img = new Image()
    img.onload = () => resolve({ url, ratio: img.naturalWidth / img.naturalHeight })
    img.src = url
});

(async () => {
    const { url, ratio } = await load("<url>");
    // Do stuff with data.
})();

To await you need the Promise.

H.B.
  • 166,899
  • 29
  • 327
  • 400