ES6: Using DataURI to provide input results in undefined output

In my current project, I am facing a challenge. I am attempting to pass image dataURI as an input from a url link to the image. To achieve this task, I know that I have to utilize canvas and convert it from there. However, since this process involves an 'async' method, I seem unable to generate a proper return value.

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

To retrieve the URI within a for loop in my class, I make use of this function.

let logo = tariff.getLogoURI();

I suspect that when calling getLogoURI(), it is automatically considered a synchronous function, thus failing to provide the expected outcome. However, I'm unsure about the exact reason behind this behavior.

Answer №1

Let's dive into the current functionality of the getLogoURI method

getLogoURI() {
  // When getLogoURI() is called, it in turn calls getLogo()
  // getLogo() returns a promise,
  // The success callback within then() is invoked upon resolving the promise
  // The then() function also returns a promise which is not being returned by getLogoURI() 
  // Hence, getLogoURI() does not return anything and defaults to undefined
  // You're seeing 'undefined' as the output for this reason
  this.getLogo().then((result) => {
    console.log(result); // This prints the correct output
    return result; // However, this actually returns undefined
  });
}

To address this issue, we need to make some adjustments:

getLogoURI() {
  // Return the promise generated by then()
  return this.getLogo().then((result) => {
    console.log(result); // This prints the correct output
    return result; // However, this actually returns undefined
  });
}

Now, getLogoURI will successfully return a promise that can be utilized like so:

getLogoURI().then(result => // Use the result here);

Wait, the modification made above essentially eliminates the need for getLogoURI. Attempting synchronous execution of async operations is impossible. I recommend exploring MDN's documentation on then for further clarification.

You could explore using async/await for a more streamlined control flow, mimicking synchronicity while staying asynchronous. Exercise caution with compatibility issues across browsers when employing async/await. With async/await, your code would look something like this:

async useLogoURI() {
  let logo = await this.getLogo();
  // Utilize the logo data at this point
}

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

The Map Function runs through each element of the array only one time

I'm new to JavaScript and experimenting with the map() function. However, I am only seeing one iteration in my case. The other elements of the array are not being displayed. Since this API generates random profiles, according to the response from the ...

The variable 'firebase' is nowhere to be found

I am encountering an issue with the error message 'Can't find variable: firebase' and I am struggling to identify the cause of this error. I have installed firebase using 'yarn add firebase' and double-checked that it is properly i ...

Storing content from external files in Angular 1.x templateCache

I am currently utilizing the Angular templateCache, following the example set in Angular's documentation. var myApp = angular.module('myApp', []); myApp.run(function($templateCache) { $templateCache.put('templateId.html', ' ...

Scroll positioning determines the height of an entity

Here's a code snippet I'm working with: HTML: <div id="wrap"> <div id="column"></div> </div> CSS: #wrap { display: block; height: 2000px; width: 400px } #column { display: block; height: 20px; ...

Displaying adornments in a vertical arrangement within a TextField using Material UI

Is there a way to display adornments vertically in a Material UI Textfield? I've been trying but it always shows up horizontally. Snippet: <TextField variant="filled" fullWidth multiline rowsMax={7} onFocus={() => h ...

The header in the fetch() function is displaying as application/x-www-form-urlencoded rather than the expected application/json

Update #2: The issue has been resolved, you can find the solution in my own answer (which I am unable to accept at this time). I have a React application running on Heroku with a node.js backend via Express. In the frontend, I am attempting to send a POST ...

What is the mechanism by which a custom hook, functioning as a trigger, initiates the re-rendering of a separate function component?

According to the official documentation on Custom React Hooks, one particular use case for utilizing a custom hook is demonstrated through the following example: function FriendListItem(props) { const isOnline = useFriendStatus(props.friend.id); retur ...

Navigate array in vue-chart.js

I've been utilizing Vue-chartjs with Laravel 5.7 for my project. The goal: I aim to pass an array to Vue so that I can dynamically generate a chart by looping through specific values. My approach so far: Here's the array I'm working with ...

Successor in a JavaScript array with multiple dimensions

I am grappling with a complex nested multidimensional array that resembles the following structure in JSON format: [ { "Object": "Car", "Child": [ { "Object": "Toyota", "Child": [ ...

Avoiding data type conversion in JavaScript/TypeScript

Currently delving into the world of JavaScript, I come from a background of working with statically typed languages. Naturally, I opted to dive into TypeScript instead of starting directly with JS. While TypeScript is great and addresses many issues presen ...

Database storage of image tags on websites, similar to functionality found on social media platforms such as Facebook

Looking for an image tagging solution for websites that can save tag data directly to a database instead of a local file? I've checked out , but it doesn't support database integration in the current version. Ideally, I need a solution that is co ...

Anonymous self-executing functions with parameters from an external scope

Recently, I stumbled upon the code snippet below while following a tutorial. const increment = (function(){ return function incrementbytwo (number){ return number+2; } })(); console.log(increment(1)); The result of the code above is 3. ...

Exploring the intricacies of debugging async/await in Node.js with the help of

Having trouble debugging an "await" instruction in my async function. Every time I try, a promise is returned instead of the expected value. I've noticed there's supposed to be an "Async" button where the red square is located in this picture but ...

AngularJS: accessing siblings by using the ng-click directive

I am currently working on a list (<ul>), which is being used in multiple instances within different ng-repeat iterations on the same page. The initial list items are generated through ng-repeat, with the second to last item containing a span. When t ...

Solving routing issues using object constructors in expressjs

Currently, I am in the early stages of developing an API REST using express and nodejs. As part of my routing process, I have decided to create separate "controllers" for each route and call these controllers within a router file. For example: ... router. ...

I encounter Error 406 and CORS issues when making API calls

I am currently engaged in a project aimed at helping my employer keep track of shipping loads, customers, carriers, and locations. The frontend is built using a react app that enables users to input information regarding loads, customers, etc. On the backe ...

Ways to determine if the user is either closing the browser or navigating to a different website

I am looking to set up session management in a manner where all sessions are expired or destroyed when the user closes the browser or tab. However, I would like to retain all the sessions if the user is navigating to another website. Is there a way to ac ...

Modifying the default text within a select box using jQuery

Within a select box identified as 'edit-field-service-line-tid', there is default text displayed as '-Any-'. This particular select field has been generated by Drupal. I am looking to use jQuery to change the text '-Any-' to ...

The placeholder feature seems to be malfunctioning when it comes to entering phone numbers in a react

I am working on a MUI phone number form field. I want the placeholder to show up initially, but disappear when the user starts typing. How can I achieve this functionality in my code? import React from "react"; import MuiPhoneNumber from " ...

execute action after a specific point in time in the video is reached

How can I hide a div after a video has been playing for a certain amount of time? The code provided below seems like it should work in theory, but is currently not doing so. Any suggestions on how to fix this issue would be greatly appreciated! <body ...