本文介绍了如何使用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))
}

我得到 undefined 因为函数运行但imaged尚未加载。

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

如何使用await / async仅在照片加载时返回值以及宽度和高度已经可用?

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

推荐答案

你没有。 。这没有语法糖。

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



你可以做

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

这篇关于如何使用async / await将此回调转换为承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 05:27