"Exploring the Use of Async Functions in AngularJS for Converting to Base64

I am currently working on developing a hybrid mobile app using angularJS and ionic as a mobile developer.

I am facing an issue with an async function where the value has to be returned after all conversions and mappings are completed. However, I keep getting null values because the conversion process takes longer than the mapping process.

I want to ensure that the mapping runs only after the conversion is done.

Below is my service code:

angular.module('file.service', ['ionic'])
.factory('fileService', ['$q', function($q) {
    var factory = {};

    factory.getContentImageFix = function(fileParsing){
        var contentImg = [];
        for(var i = 0; i < fileParsing.length; i++){
            convertFileToDataURLviaFileReader(fileParsing[i].fullpath, function(base64Img){
                contentImg.push({
                    image: base64Img,
                    width: 400
                });
            });
        }
        return $q.all(contentImg);
    }

    function convertFileToDataURLviaFileReader(url, callback){
        var xhr = new XMLHttpRequest();
        xhr.responseType = 'blob';
        xhr.onload = function() {
            var reader  = new FileReader();
            reader.onloadend = function () {
                callback(reader.result);
            }
            reader.readAsDataURL(xhr.response);
        };
        xhr.open('GET', url);
        xhr.send();
    }
}]);

And here is how my controller looks like:

angular.module('scan.module’, ['ionic'])
.controller('scanController’, [‘fileService’, function(fileService) {
    var fileParsing = [
        {
            “name”:”a.jpg",
            "fullpath”:”[PATH]/a.jpg"
        },{
            "name”:”b.jpg",
            "fullpath":"[PATH]/b.jpg"
        }
    ];
    var contentImg = fileService.getContentImageFix(fileParsing);
    console.log(JSON.stringify(contentImg)); //it currently returns an empty array
}]);

I am not very familiar with the concept of promises. Can someone guide me on how to solve this async problem?

Thank you.

Answer №1

In order to utilize $q.all() with an array of promises, you can modify the convertFileToDataURLviaFileReader function to return a promise. Here's an example:

function convertFileToDataURLviaFileReader(url){
    var defer = $q.defer();
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
        var reader  = new FileReader();
        reader.onloadend = function () {
            defer.resolve(reader.result);
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.send();
    return defer.promise;
}

You can then use this modified function in your factory like so:

factory.getContentImageFix = function(fileParsing){
    var contentImg = [];
    for(var i = 0; i < fileParsing.length; i++){
          contentImg.push(convertFileToDataURLviaFileReader(fileParsing[i].fullpath));
    }
    return $q.all(contentImg);
}

Finally, in your controller, you can call getContentImageFix and handle the returned data like this:

fileService.getContentImageFix(fileParsing).then(function(contentImg){
    console.log(JSON.stringify(contentImg))
})

Answer №2

It seems like the original solution provided was not effective:

http://plnkr.co/edit/SXKNbBc2b32UTzYIVsrB?p=preview

  FileService.getContentImages(files).then(function(images) {
    $timeout(function() {
      mv.images = images;

      console.log(images);
    }, 0);
  });

I encountered an issue with updating async data during the current $digest cycle, which I resolved by implementing a simple timeout.

Additionally, I opted to utilize a directive for improved functionality, as directives tend to outperform controllerAs in div elements :)

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

Guide to making loop transition animations using CSS transforms

Looking for help with creating a loop animation transition using CSS transform. I've developed a basic slider that utilizes transform to move items. The issue arises when I shift to the right, and the translate value goes from translate3d(-544px, 0px ...

What is the best way to ensure that the state is updated only when the user begins typing in a text

I am currently working on a text editor-related code and my main focus is to update the state of the editor only when the user starts typing in the editor. The state should be updated under the following scenarios: 1. Update the state when the user begin ...

"Enhance your website with the powerful autocompletion feature of

I am using Zend Framework to create a form element that utilizes Zend_Dojo_Form_Element_ComboBox. By setting dojox.data.QueryReadStore as the store type, I am able to generate a list of selectable values in my HTML input field. This allows me to either cho ...

Looping through elements with jQuery's `each` method within another `

When using div containers in my code, I wanted to loop over them and then iterate through the items within each container. Instead of $('.stackContainer .stackItem').each(, I was looking for a solution like this: // setup stacks $('.stackC ...

Ensure that data is not cached after the page is refreshed at regular intervals of x seconds

In the process of developing a news app, I have implemented a feature where a div with the class .new_feed is refreshed every 10 seconds to fetch new updates. However, I encountered an issue where if a new feed appears in the .new_feed div and is not cli ...

Tips on successfully executing the swap method in the JustSwap smart contract

I'm attempting to finalize the JustSwap-contract S-USDT-TRX Token (TQn9Y2khEsLJW1ChVWFMSMeRDow5KcbLSE), but I keep receiving a "REVERT opcode executed" response in the console. My code: const TronWeb = require("tronweb"); const ethers ...

Typehead Twitter: A dynamic list of object arrays

Experiencing an issue while implementing the Twitter Typehead feature with an object array. For a demonstration, please check out the JSBin provided at http://jsbin.com/buyudaq/edit?html,js,console,output Below is the serialized object array containing p ...

What is a more efficient way to avoid duplicating code in javascript?

Is there a way to avoid repeating the same code for different feeds? I have 8 feeds that I would like to use and currently, I am just incrementing variable names and feed URLs. <script type="text/javascript> function showFeed(data, content ...

Mystery Surrounding MP3 Playback in ASP.NET

Currently, I am utilizing an ASP.NET server side control to play MP3 files on my website. While I could utilize JavaScript or Flash controls for this purpose, the issue I'm facing is that I want the music to only play once (at the start of the site) a ...

Retrieve the name of the page instead of the page number using PHP in combination with AJAX

I found a helpful tutorial on using AJAX to load content on a website. However, the tutorial uses generic page names like "page1, page2, page3, etc." and I want to use specific page names like "products, about, etc.". I've been working on the code in ...

I am experiencing an issue where my Laravel website does not refresh automatically

Having trouble with the URL (url: "/ultimo-pedidox"). It seems to be loading correctly, but the view isn't refreshing as expected. @extends('store/template') @section('content') <div style="margin-top: 55px;" ...

Navigation bar with a full-page slider

I am trying to incorporate my bootstrap nav bar into a full-width slider, similar to the layout in this example. https://i.sstatic.net/LE9wP.jpg This is the full width slider http://codepen.io/grovesdm/pen/MazqzQ Currently, I have positioned the nav ba ...

Creating personalized categories with Material-UI's Autocomplete feature in a React application

I've been attempting to customize the groupings in the MUI Autocomplete component, but I haven't had any luck so far. It seems like there is no built-in solution provided by the library (I hope I'm mistaken). https://i.sstatic.net/NcJWU.png ...

Pinterest-style Angular-UI-Router modal

I am currently working on an app that features a gallery showcasing similar functionalities to . In Pinterest, clicking on a pin displays the pin page above the existing gallery without any information about the background gallery shown in the URL. Users c ...

Encountering the "Uncaught TypeError: Cannot read properties of undefined (reading 'map')" error message while implementing Chart.js within a React Axios function

Struggling with creating a Chartjs chart in React using Axios post method to retrieve data from a Nodejs server. However, encountering the following error: "Uncaught TypeError: Cannot read properties of undefined (reading 'map')" Here's a s ...

Is it possible that event.returnvalue=false is causing issues in Firefox?

Currently, I am updating an outdated application to ensure it works seamlessly on Firefox. Since the original application does not utilize Jquery, I need to rely solely on Javascript for all my modifications. One of the tasks involves restricting input in ...

Utilizing jQuery xmlParser to display search results customized by slider controls or selection buttons

Currently, I am exploring ways to customize the output of my xmlParser in terms of the number of data results returned. Through my experimentation, I discovered that using: :lt() such as this: $(xml).find("override:lt(10)").each(function () { allows m ...

Ways to retrieve the context of a function caller?

I'm exploring the concept of JavaScript scopes and am curious about a specific scenario: // B has access to 'context' var x = function (context) { y = function () { console.log(context); }; y(); }; x('cool'); ...

Having trouble with using findByIdAndUpdate and push in MongoDB?

As someone who is new to Mongodb, I have been using the findByIdAndUpdate function to update a document in my project. However, I noticed that it returns the old document instead of the updated one. Below is the code snippet of my function: exports.crea ...

What is the best way to vertically align Angular Material tabs?

In my current project, I decided to use angular material and encountered a problem with the angular material tab. I wanted to arrange the tabs vertically, but it doesn't seem to be working properly. The alignment seems off and it's not functionin ...