【问题标题】:Async await now working in Nuxt component异步等待现在在 Nuxt 组件中工作
【发布时间】:2021-09-24 10:28:36
【问题描述】:

我有两个功能, 一个函数将图像从任何格式转换为画布,然后转换为 WEBP 图像格式。 另一个函数接收图像和console.log图像。

问题是当我在saveToBackend函数中记录图像的结果时,我得到一个未定义的结果,但是当我在console.logconvertImage函数中转换图像时,我得到了图像。请问我该如何解决这个问题?

以下是我的 NUXT 应用程序中的功能

        convertImage(file) {
            // convert image
            let src = URL.createObjectURL(file)
            let canvas = document.createElement('canvas');
            let ctx = canvas.getContext('2d')

            let userImage = new Image();
            userImage.src = src

            userImage.onload = function() {
                canvas.width = userImage.width;
                canvas.height = userImage.height;
                ctx.drawImage(userImage, 0, 0);

                let webpImage = canvas.toDataURL("image/webp");
                console.log(webpImage); // with this i get the image in the console
                return webpImage
            }
        },
        async saveToBackend(file, result) {
            // convert images to webp
            let webpFile = await this.convertImage(file)
            console.log(webpFile); // with this i get undefined in the console
        }

【问题讨论】:

  • convertImage 既不是async 也不是返回一个承诺,所以awaiting 它什么也不做。

标签: javascript vue.js nuxt.js


【解决方案1】:

您不能从 onload 回调中返回 webpImage。它根本不会等待onload 执行。您可以改为创建一个Promise,当onload 完成时解析webpImage 的值:

convertImage(file) {
  return new Promise((resolve) => {
    // convert image
    let src = URL.createObjectURL(file);
    let canvas = document.createElement("canvas");
    let ctx = canvas.getContext("2d");

    let userImage = new Image();
    userImage.src = src;

    userImage.onload = function() {
      canvas.width = userImage.width;
      canvas.height = userImage.height;
      ctx.drawImage(userImage, 0, 0);

      let webpImage = canvas.toDataURL("image/webp");
      console.log(webpImage); // with this i get the image in the console
      // resolve promise so that saveToBackend can await it
      return resolve(webpImage);
    };
  });
}

希望对您有所帮助!

【讨论】:

  • 兄弟,谢谢你的回答,我从中学到了一些新东西。我会把它标记为正确的。
猜你喜欢
  • 2021-11-01
  • 2014-06-06
  • 1970-01-01
  • 2021-10-22
  • 2019-01-13
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
  • 2019-07-23
相关资源
最近更新 更多