简体   繁体   English

如何使用 async/await 将此回调转换为承诺?

[英]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:以下函数从 url 获取图像,加载它,并返回其宽度和高度:

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.我得到undefined因为函数运行但图像尚未加载。

How to use await/async to return the value only when the photo has loaded and the width and height is already available?仅当照片已加载且宽度和高度已可用时,如何使用 await/async 返回值?

How to use async / await to turn this callback function into a promise?如何使用async / await将这个回调函数变成一个 promise?

You don't.你没有。 As usual, you use the new Promise constructor .像往常一样,您使用new Promise构造函数 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?仅当照片已加载且宽度和高度已经可用时,如何使用await / async来记录值?

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

这个库工作得很好 - 它允许连接到子进程,或者如果需要,只需异步返回结果: https : //github.com/expo/spawn-async

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM