Nuxt component successfully implemented with async await functionality

Managing two distinct functions, where one converts images from any format to canvas and then to WEBP image format, while the other logs the converted image. I am encountering an issue where the result of the image is undefined when logged in the saveToBackend function. However, when I log the converted image within the convertImage function, it displays correctly. How can this problem be resolved?

Displayed below are the functions utilized in my NUXT app:


        convertImage(file) {
            // Image conversion process
            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); // Image displayed correctly in console
                return webpImage
            }
        },
        async saveToBackend(file, result) {
            // Image conversion to webp format
            let webpFile = await this.convertImage(file)
            console.log(webpFile); // Displays 'undefined' in the console
        }

Answer №1

One cannot directly return webpImage within the onload callback as it will not wait for the execution of onload. To address this, you can create a Promise that resolves the value of webpImage once onload is completed:

convertImage(file) {
  return new Promise((resolve) => {
    // image conversion process
    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); // printing the image in the console
      // resolve the promise to enable await in saveToBackend
      return resolve(webpImage);
    };
  });
}

I hope this explanation is helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for excluding a value in a Vue loop

Is there a way to exclude the value "Three" from the loop in the following code snippet? <script > const routes = [ {name: 'One', value: 24}, {name: 'Two', value: 25}, {name: 'Three', value: 26}, {name: ...

Encountering generator crashes when using Vue Cli remote presets

While attempting to develop a remote Vue CLI preset on GitHub, I encountered a syntax error that I cannot seem to resolve. You can find my preset repository here: https://github.com/christoph-schaeffer/vue-preset The command I entered is as follows: vue ...

Modify an element upon clicking the mouse on an image

I am looking to dynamically change the paragraph element with className="details" to an editable input field when a user clicks on the image with className="edit-icon" within the same grid container. How can I achieve this functionality ...

Exploring the Fusion of Strings and Arrays of Javascript Objects using jQuery and JSON

Trying to achieve a simple task, but not very proficient in jQuery so struggling to figure it out. Want to send JSON data to an ASP.NET Controller. Data includes strings and a list of objects. The code snippet would appear like this: View: $(document). ...

The module 'nodemailer' could not be located

Currently working with the Zapier Code tool, my goal is to send an email with Trello parameters. I've been using JavaScript encoding in combination with node.js for this task. However, every time I attempt to locate the 'nodemailer' module, ...

Saving JSON format in VueX State Management

I'm relatively new to using Vue/VueX and I am exploring methods for storing JSON data in the VueX state. Initially, it seemed like a simple task: state { jsonthing: { ... } } However, I encountered an issue where getters return an Observer type ins ...

"Troubleshooting Error: When accessing a property in AngularJS,

My goal is to retrieve a date value. However, I encounter an error message saying 'Cannot read property 'NTLI' of undefined' whenever the checkbox is unchecked and the date picker is invisible. Strangely enough, everything works fine wh ...

Identify any missing periods and combine the years into a single range

I am working on restructuring year ranges with gaps and consolidating them. For example, converting [{start: 2002, end: 2020}, {start: 2020, end: null}] to {start: 2002, end: null} or [{2002, 2004},{2006, 2008}, {2008, null}] to [{2002-2004}, {2006-null}]. ...

Creating beautiful user interfaces with Material UI and React

I'm currently exploring how to integrate Material UI into my React project. After successfully installing the module, I attempted to create a custom button component. Here is my Button.js file: import React from 'react'; import FlatButton ...

Tips for adding styling to HTML in Vue by entering CSS code into the CodeMirror editor

Is there a way to style HTML by entering CSS code into the Codemirror editor? For instance, if we have the HTML code <head> </head>, how can I apply the CSS code, head{ color : red }, typed in the Codemirror editor to stylize this HTML code? mo ...

Employing the findOne method repeatedly in a loop can significantly slow down operations in Node.js

Currently, I am working on a project using Node.js in conjunction with MongoDB, specifically utilizing Monk for database access. The code snippet I have is as follows: console.time("start"); collection.findOne({name: "jason"}, function(err, document) { ...

The challenges of implementing view changes with $state.go

In the code below, I am setting up a login process. The PHP file for this process is working correctly, but after successful login, the view does not change as expected: (function (){ var app = angular.module('starter', ['ionic']); va ...

Sending the child state value to the parent state array

I have successfully implemented the react-select component on a GitHub page, specifically a multiselect component similar to the one found in the example provided at this link. Everything is working as expected, but I am facing an issue when trying to pass ...

Binding in Angular JS seems to be having some issues

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap 101 Template ...

What could be causing the malfunction in my JavaScript random selector?

Can anyone assist me with this issue? I'm attempting to implement JavaScript functionality to highlight randomly selected picks that I input, but it's not functioning correctly. Every time I inspect my JS code on the webpage, I encounter an erro ...

What is the method for arranging objects in AngularJS using a custom sorting sequence?

I would like to display an array of object's properties in a custom sorted order. Here is the initial array: $scope.weekDays = [ { "day" : "TUESDAY", "count": 10 }, { ...

The value being passed as a parameter is a number, which cannot be assigned to a parameter expecting a Date type

I'm currently in the process of testing a function by passing a date as a parameter, but I seem to be encountering an issue that I can't quite figure out. When structured like this, it throws an error stating "Argument of type 'number' ...

Is it possible to use JavaScript for detecting third-party videos?

I'm currently developing an HTML5 video player that also has a fallback to flash. One of the challenges I am facing is that the video content is being provided by various third-party sources. It seems that some of these third parties serve videos bas ...

When activating another function, Javascript failed to trim and hide the div as intended

Before adding another function (*2), my function (*1) was working perfectly. However, after adding the second function, there seems to be a conflict and now it's not working as expected. :( <script type="text/javascript> $(function() { ...

Utilizing jquery to showcase the information in a neat and organized table

Having an input text box and a button, I am looking to display dummy data in a table when any number is entered into the input field and the button is clicked. Here is what I have tried: My Approach $("button#submitid").click(function () { $(&quo ...