Javascript ES6将DataURI作为输入传递-返回未定义

Javascript ES6将DataURI作为输入传递-返回未定义,javascript,asynchronous,ecmascript-6,data-uri,Javascript,Asynchronous,Ecmascript 6,Data Uri,我试图通过url链接将图像数据URI作为输入传递给图像。我明白要做到这一点,我必须使用画布,并从那里转换它。然而,由于这是一个“异步”方法,我无法生成返回 getLogo() { let image = new Image(); let canvas = document.createElement('canvas'); return new Promise((resolve) => { image.onload = () => {

我试图通过url链接将图像数据URI作为输入传递给图像。我明白要做到这一点,我必须使用画布,并从那里转换它。然而,由于这是一个“异步”方法,我无法生成返回

    getLogo() {
    let image = new Image();
    let canvas = document.createElement('canvas');
    return new Promise((resolve) => {
      image.onload = () => {
        canvas.width = image.naturalWidth;
        canvas.height = image.naturalHeight;
        canvas.getContext('2d').drawImage(image, 0, 0);
        let uri = canvas.toDataURL('image/png');
        resolve(uri);
      };
      image.src = this.logo;
    });
  }

  getLogoURI() {
    this.getLogo().then((result) => {
      console.log(result); // the correct output writes here
      return result; // this returns undefined
    });
  }
然后我从我需要URI的类中调用它,这在for循环中

let logo = tariff.getLogoURI();

我相信在调用getLogoURI()时,它会自动将其视为一个同步函数,因此不会返回正确的值,但我不确定。

让我解释一下当前使用的
getLogoURI
方法

getLogoURI() {
  // when getLogoURI() is invoked, it calls getLogo()
  // getLogo() returns a promise,
  // whose then is being invoked with a success callback, which will be invoked on resolving of promise
  // then() function returns a promise which is not being returned by getLogoURI() method
  // so getLogoURI() method is not returning anything
  // if a function do not return any thing then undefined is returned by default
  // that's why you are receiving undefined
  this.getLogo().then((result) => {
    console.log(result); // the correct output writes here
    return result; // this returns undefined
  });
}
为了解决这个问题,我们可以做一些改变

getLogoURI() {
  // return promise being returned by then()
  return this.getLogo().then((result) => {
    console.log(result); // the correct output writes here
    return result; // this returns undefined
  });
}
现在
getLogoURI
将返回一个承诺,我们可以这样使用它

getLogoURI().then(result => //use result here);
async useLogoURI() {
  let logo = await this.getLogo();
  // use logo here
}
等等,这是我们在
getLogoURI
中已经做过的,这意味着
getLogoURI
只是一个无用的包装器,您不需要使用它。您试图实现它的方式是不可能的,因为这些是可以同步完成的异步操作。我希望阅读MDN的,然后将有助于你理解它

您可以使用/来简化控制流,它看起来很像同步流,但它完全是异步的。请谨慎使用,因为它可能与某些浏览器存在兼容性问题。使用async/await,上述代码如下所示

getLogoURI().then(result => //use result here);
async useLogoURI() {
  let logo = await this.getLogo();
  // use logo here
}
可能重复的