异步等待图像onload事件触发器

时间:2018-03-26 18:30:39

标签: javascript ecmascript-6 async-await

我有一个奇怪的,我无法包裹我的大脑。

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

我应该如何使用async / await,因为onload只是一个回调任务...我被困在以下地方:

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

}

是否可以在不使用resolve方法的情况下解决?

1 个答案:

答案 0 :(得分:-2)

我在第二段代码中没有得到你想要做的东西,但是上面的代码工作正常,可以像这样使用:

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

等待你需要承诺。