AngularJS Error: Attempting to access 'then' property of an undefined value

I have a function set up in my AngularJS service:

var readFile = function (path, file) {
            console.info("Attempting to read the file with URI: " +path+ " "+file);
            $cordovaFile.checkFile(path, file).then(function (success) {
                console.log(success);
                var deferred = $q.defer();
                $cordovaFile.readAsText(path, file)
                    .then(function (success) {
                        // success
                        console.log("Success");
                        console.log(success);
                        deferred.resolve(success);
                    }, function (error) {
                        console.error(error);
                        deferred.reject(error);
                    });
                return deferred.promise;
            }, function (error) {
                console.log(error);
            });
        }

In the success callback, there is a function defined for reading the file.

However, I keep encountering an exception message at this location:

TypeError: Cannot read property 'then' of undefined

But when I modify the code like this:

$cordovaFile.checkFile(path, file).then(function (success) {
                console.log(success);

            }, function (error) {
                console.log(error);
            });

it works without any issues.

I want to only execute the file reading if the file exists, but I'm unsure of the correct approach to take.

The service method is called like so:

DeviceSrv.readFile(cordova.file.externalRootDirectory+"/"+APP_CONST.MP3_FOLDER_NAME+"/sounds/", APP_CONST.MP3_FILE_NAME)
                .then(function(value){
                    console.log(value);
                    var parsedObject = JSON.parse(value);
                    console.log(parsedObject);
                    $scope.availableSounds = parsedObject.availableSounds;
                    $scope.availablePrepreparedSounds = parsedObject.availablePrepreparedSounds;
                });

How should I update my code to ensure it runs correctly?

Thank you for any advice provided.

Answer №1

One advantage of promises is that they can be chained, eliminating the need to create deferred objects.

const readFile = (path, file) => {
    console.info("Attempting to read file with URI: " +path+ " "+file);
    return $cordovaFile.checkFile(path, file)
        .then(success => $cordovaFile.readAsText(path, file))
        .then(success => {
            console.log("Success");
            console.log(success);
        })
        .catch(error => console.error(error));
}

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

Loop through an array that holds another array in javascript

After making a post request, I am receiving the following object: "{\"Success\":false,\"Errors\":{\"Name\":[\"The Name field is required.\"],\"Id\":[&b ...

Embed the component into the array collection

I have an array and I want to display a random component inside it. Specifically, I want to include the FeedbackComponent before the last two objects in the array. This is how it should look like in a schematic representation: storyObject storyObject st ...

Every time Chrome on Android returns a keyCode of 229

Here is a snippet of code that I am having trouble with: ... @HostListener('keydown', ['$event']) onKeyDown(evt: KeyboardEvent) { console.log('KeyCode : ' + evt.keyCode); console.log('Which : ' + evt.which); ...

Partial data sent through Ajax to PHP file

Encountering a peculiar issue with Ajax where the entire string data is not being sent to the php script. Here is the string: "<p class="MsoNormal" style="text-align:justify"><b><u><span lang="DE" style="font-size:10.0pt;mso-bidi-fon ...

Transferring and displaying messages between PHP scripts

On my page (index.php), I have a simple layout consisting of two DIVs. The left side (#leftDIV) contains a form and another DIV (#messages) for displaying error messages. On the right side, there is another DIV (#mapAJAX) which houses a PHP script responsi ...

Modify the CSS using JavaScript after a brief delay

I'm creating a homepage that includes animations. Inside a div, I initially have display: none, but I want it to change to display: block after a few seconds. I've been trying to use JavaScript for this purpose, but I'm struggling to find th ...

Merging Objects and inserting them into an array - Harnessing the power of JavaScript and

Having various objects stored in an array, each with a unique labelId assigned to them. Whenever there are matching label ids, the goal is to merge these objects together by consolidating some values inside a new combined object array. [ { fi ...

Experiencing difficulties embedding SoundCloud with AngularJS

I've been working with Soundclouds API to fetch the uri/permalink_url and utilize their embed layout. However, I continuously encounter this error message. Error: [$interpolate:noconcat] Error while interpolating: https://w.soundcloud.com/player/?url ...

how to sort arrays in javascript

When it comes to filtering items based on specific criteria like fruit and vegetable filters, what is the most effective method to retrieve items that meet both filter requirements? fruitfilter: [] = [{fruitname: "apple"} , {fruitname: "orange"}] vegeta ...

What is the best way to display toastr messages in an Angular application?

Can you guide me on how to include toastr in an angular app? Currently, I am enrolled in the Angular Fundamentals course and trying to use toastr.success within my export class: handleThumbnailClick(eventName){ toastr.success(eventName) } But, I kee ...

How can I prevent a block of white space from collapsing in CSS, without relying on the presence of a DIV element?

I am facing an issue with maintaining space above the Title in my design. The design includes elements like Title, Description, and Image. The challenge is to ensure that there is a 20px space above the Title, as shown in the example below: https://i.ssta ...

Can a constant value be dynamically defined in Typescript?

Trying to dynamically define a constant in Typescript has proven to be more challenging than I anticipated. Here's what I attempted: define(name: string, value: any): boolean { var undef; const name = value; return name == undef; } ...

Creating a sidebar that remains fixed in place even as the page is scrolled down can be achieved by using CSS and positioning properties

I am looking to create a website with a specific layout design as shown in this image: https://i.stack.imgur.com/ndKcz.png The main focus is on making the sidebar (F/T container) function as a social network link, sticking to the right side of the page ev ...

How to effectively utilize TypeScript in a team environment using both Atom and VSCode?

Our team utilizes TypeScript with both Atom and VSCode as our editors, but we are facing challenges with the tsconfig.json file. VSCode is not recognizing the typings, causing the namespace for 'ng' (for Angular 1.x) to be unknown in VSCode. Wh ...

Discover the method for converting a local file into a string

Looking to retrieve and read an SVG file in Angular 6 from the assets folder as a string. I've attempted the following: this._htmlClient.get('../../assets/images/chart1.svg').subscribe(data => { console.log('svg-file: ', ...

Is there a way to access the state value within the reducer function of createSlice?

Currently, I am utilizing redux-toolkit within my react project. A concern arises in a specific reducer inside the createSlice method where I aim to incorporate an existing array of entities from the state and then merge it with a new array before finalizi ...

Inquiry regarding the setTimeout function requiring an answer

I have a question about how setTimeout works. Does it wait for the previous code to finish executing before moving on to execute something else after a set time, or does it simply wait for a specific amount of time and then continue with the rest of the co ...

Tips on placing an li element into a designated DIV

Just starting out with jquery and working on a slider project. Here's what I have so far: <ul> <li> <img src="image.jpg"><p>description of the current image</p></li> <li> <img src="image.jpg"> ...

Is the "Illegal invocation" error popping up when using the POST method in AJAX?

Is there a way to retrieve JSON data using the POST method in Ajax? I attempted to use the code below but encountered an error: TypeError: Illegal invocation By following the link above, I was able to access JSON-formatted data. However, please note th ...

Clear HTML

Is there a way to create a 'div' element in an HTML document and adjust the background transparency using CSS or Javascript/JQuery in order to achieve a look similar to Simple Calendar Widget or Glass Widgets from Android? I have tried using the ...