deliver a promise with a function's value

I have created a function to convert a file to base64 for displaying the file.

 ConvertFileToAddress(event): string {

    let localAddress: any;
    const reader = new FileReader();
    reader.readAsDataURL(event.target['files'][0]);
    reader.onload = (e) => {
        localAddress = e.target['result'];
    };
    return localAddress;
}

I am trying to use this function in other components like this:

this.coverSrc=this.localization.ConvertFileToAddress(event);

However, when I log this.coverSrc to the console, it shows me undefined.

When I log within this bracket:

    reader.onload = (e) => {
        localAddress = e.target['result'];
    };

It displays the value of base64. But when I log localAddress outside of the bracket, it shows me undefined.

DEMO

How can I properly return the value from the function and use it in other components?

Answer №1

To solve this issue, you have the option of using either Promises or callbacks.

-- Implementing Callbacks

ConvertFileToAddress(event, callback): string {
    const reader = new FileReader();
    reader.readAsDataURL(event.target['files'][0]);
    reader.onload = callback;
}

this.localization.ConvertFileToAddress(event, (e) => {
     this.coverSrc = e.target['result'];
});

-- Utilizing Promises

ConvertFileToAddress(event): string {

    return new Promise((resolve, reject) {

        const reader = new FileReader();
        reader.readAsDataURL(event.target['files'][0]);
        reader.onload = (e) => {
             resolve(e.target['result']);
        };
    });
}

this.localization.ConvertFileToAddress(event).then((data) => {

   this.coverSrc = data;
});

You can also explore using Observables - check out a sample here:

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

Issues arise when attempting to alter the background image using jQuery without browserSync being activated

I am facing an issue with my slider that uses background-images and BrowserSync. The slider works fine when BrowserSync is running, but without it, the animations work properly but the .slide background image does not appear at all. Can someone help me ide ...

The process of utilizing RxJS for server polling is a

My goal is to constantly update client-side data by polling the server. To achieve this, I have set up a dispatcher that triggers an action labeled FRONT_PAGE. This action is initiated when the app launches and the client is supposed to send requests every ...

Error: An issue occurred with the tasks in the Gruntfile.js file

pm WARN EPACKAGEJSON <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74041506001a1106041b0600151834445a445a44">[email protected]</a> No description npm WARN EPACKAGEJSON <a href="/cdn-cgi/l/email-protection" ...

Utilizing TypeScript in a browser with a .NetCore WebApplication

After going through numerous articles, I have not been successful in finding a solution. My challenge lies with a .net core WebApplication that utilizes typescript code instead of javascript. Here are the specific requirements: I need to be able to debu ...

Having trouble with proper routing using node.js, socket.io, and the __dirname variable

As a newcomer to node.js, I am struggling with creating a basic route to read a file using node.js and socket.io. The solution may be straightforward, but I feel like I'm missing some fundamental concepts here. var http = require('http' ...

AngularJS ng-focus does not function properly with iframes

Why isn't ng-focus working with iframe in AngularJS? What am I missing? Take a look at my code: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <iframe src="example.com" tabindex="-1" ng-fo ...

Is it possible to reduce the number of calls to ngAfterContentChecked() and ngAfterViewChecked() instead of calling them repeatedly?

`ngAfterContentChecked() { console.log("Content has been checked"); } ngAfterViewChecked(){ console.log("View has been checked"); }` I am currently developing an Angular project where I need to execute a set of statements twice on a page - ...

Trouble with $http response not appearing in AngularJS application

Currently, I am in the process of developing an angularjs application and encountering a challenging issue with setting up the $http connection to a php file. The header is displaying a response that I echoed from php. Nevertheless, two key problems persis ...

Downloading a file through a JavaScript link in HTMLUnit: A step-by-step guide

Looking to download a file with HTMLUnit from a javascript link is proving to be quite challenging. The journey begins at this page. When clicking on the "Authenticate with Java Web Start (new method)" link, a .jnlp file is downloaded, initiating a Java pr ...

The process of altering the color of a table row in JavaScript can be done after dismissing a pop-up that was triggered by a button within the same row

I am tasked with changing the color of a specific table row based on user interaction. The table consists of multiple rows, each containing a button or image. When the user clicks on one of these buttons or images, a popup appears. Upon successful data sub ...

JavaScript keydown event for rotating images

I am experiencing an issue with JavaScript animation. I have incorporated code from this particular link into my keydown function. However, the code is not functioning as expected. While the code from the provided link works fine on its own, within the key ...

Navigating with router.push in Vue.js to the same path but with different query parameters

The existing URL is /?type=1 I am attempting to implement router.push on this specific page. this.$router.push('/?type=2'); However, it results in a NavigationDuplicated error. I prefer not to utilize parameters such as /:type ...

No default export found in Module: TypeScript RestAPI

The word controller is showing a red underline when I use import controller from '../controllers/test.controller'; In my typescript rest api application, the structure looks like this... project structure I am puzzled by the red line under cont ...

Show the components only if the final digit in their identification number is less than i

I have several span elements with IDs like "tag1", "tag2", etc. I want to display only the spans whose ID ends with a number less than 19. These elements are part of a class called "notVis", which is hidden by default using $(".notVis").hide(); when the ...

Can you explain the distinct variations between these two approaches for obtaining API data?

When working with third-party APIs in NextJS 14, I encountered two different methods to query the API that resulted in slightly different outcomes. Method 1: Located within the /api folder as a route handler: export async function GET() { const res = aw ...

After closing, the position of the qtip2 is being altered

I've successfully integrated the qtip2 with fullcalendar jQuery plugin, which are both amazing tools. However, I'm encountering an issue with the positioning of the qtip. Here's the code snippet I'm using: $(window).load(function() { ...

Encountering net::ERR_CONNECTION_RESET and experiencing issues with fetching data when attempting to send a post request

I am facing a React.js task that involves sending a POST request to the server. I need to trigger this POST request when a user clicks on the submit button. However, I keep encountering two specific errors: App.js:19 POST http://localhost:3001/ net::ERR_CO ...

Create dual modules within a single project

I am working on a mean-stack project. In my index.js, at the end, I have: router.get('*', function(req, res) { res.sendfile('./views/index.html'); }) module.exports = router; Now, I need to handle all webpages that match https://l ...

Error: the search variable is not defined

function sorting(type) { $("#parentDiv").empty(); $.getJSON("example_data.json", ({ Find })); function Locate(a, b) { return (a[Find.type] < b[Find.type]) ? -1 : (a[Find.type] > b[Find.type]) ? 1 : 0; }; } The example_data.j ...

Steps for adding a React Class Component into a Modal that is not within the React Tree

Our project is built using PHP MVC Framework and we initially used jQuery as our main JavaScript framework for handling UI activities. However, we have now transitioned to using React.js. My query is about how to inject or append a React Functional/Class-b ...