"Indecipherable Outcome: JavaScript's En

Just starting out with Javascript and AngularJS, I'm on a learning journey. I created an angular service to handle DB queries and return promises.

        executeStatement = function(db, sql, values, onsuccess, onerror) {
        if (!!db.executeSql) {
            return db.executeSql(sql, values || [], onsuccess, onerror);
        } else {
            return db.transaction(function(tx) {
                return tx.executeSql(sql, values, function(ignored, rs) {
                    return onsuccess(rs);
                }, function(ignored, error) {
                    return onerror(error);
                });
            });
        }
    };

    this.executeStatement = function(sql, values) {
        $ionicPlatform.ready( function() {
            return new Promise(function(resolve, reject) {
                return executeStatement(myDB, sql, values, resolve, reject);
            });
        } );
    }

After calling the executeStatement method like this in the angular service module:

    this.extract = function(callback) {
        _DB.executeStatement('SELECT * FROM FRIDGE', []).then(callback);}

Shouldn't this provide a promise once the functions have completed? I keep getting undefined :( Any help would be greatly appreciated!

Answer №1

In order for the this.executeStatement() function to properly function, it is crucial that it returns the output of $ionicPlatform.ready():

this.executeStatement = function(sql, values) {
    return $ionicPlatform.ready( function() {
        return new Promise(function(resolve, reject) {
            return executeStatement(myDB, sql, values, resolve, reject);
        });
    } );
}

By doing this, you will be able to utilize whatever is returned from the executeStatement in your callback, which can then be passed as an argument to the .then() function:

_DB.executeStatement('SELECT * FROM FRIDGE', []).then(callback);

Answer №2

When working with the function executeStatement, it is important to note that the functions within are not explicitly defined as Promise. Therefore, they do not require a specific return statement. Instead, the onFulfilled and onRejected parameters of the Promise constructor are passed to a function. This allows for the resolution or rejection of the original Promise when onsuccess or onerror are invoked.

To handle any potential errors within the Promise chain, it is recommended to include a second parameter in the chained .then() method or utilize the .catch() method.

If you are uncertain whether $ionicPlatform.ready returns a Promise, it would be worthwhile to verify this detail.

_executeStatement = function(db, sql, values, onsuccess, onerror) {
    if (!!db.executeSql) {
        db.executeSql(sql, values || [], onsuccess, onerror); 
    } else {
        db.transaction(function(tx) {
            tx.executeSql(sql, values, function(ignored, rs) {
                onsuccess(rs);
            }, function(ignored, error) {
                onerror(error);
            });
        });
    }
};

this.executeStatement = function(sql, values) {
    return $ionicPlatform.ready( function() {
             return new Promise(function(resolve, reject) {
               _executeStatement(myDB, sql, values, resolve, reject);
             })
             .catch(function(err) {
               // handle, pass error here
               console.log(err);
               return err
             })
           });
}

this.executeStatement(/* parameters */)
.then(function success(data) {
  console.log(data);
}, function err(err) {
  console.log(err);
});

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

How do I implement zoom functionality in Three.js using a function?

My current scene includes Trackball Controls, and I am looking to add a zoom button that triggers a custom JavaScript function to implement zooming in addition to the standard mouse zooming functionality. What steps should I take to achieve this desired ...

Confirm that a collection is empty using node.js

const http = require('http'); const url = require('url'); const route = require('router')(); ... route.get('/{betNameType}', function(req, res) { const query = url.parse(req.url, true).query; if (!Object.keys ...

Ensuring the validation of checkboxes using the Bootstrap framework

I am currently working on validating checkboxes using JavaScript. If the validation fails, I want to display a div with the class invalid-feedback below the checkboxes. However, when I add the invalid-feedback class to my div, it simply disappears. < ...

Eliminate any blank spaces in the SELECT Angular application for IE-CSS

One issue I encountered is removing the default selected "SELECT" option from a select drop down on my webpage. Currently, I am using to remove it successfully in Chrome and Firefox browsers, but unfortunately IE does not respond to this method. I ha ...

Tips on mocking Mongoose model functions in tests using sinon

I have a function called getTask() that is structured like this: const Task = require('./model'); const User = require('../users/model') module.exports = async function getTask (key) { const task = await Task.findOne({key}).exec() ...

Repeatedly invoking the debounce function

When invoking the searchkeyword function on keyUp, my goal is to prevent or clear the timeout of $emit when a new letter is quickly typed. This way, I only want $emit to be called a few times. However, currently, the console triggers debounce on every se ...

Angular: An excessively large number of dynamically generated FormGroups within a FormArray is causing the webpage to become unresponsive

In my project, I have implemented a dynamic FormArray generation process which is triggered by the following code snippet. this.priceListForm.addControl('priceListLines', this.formBuilder.array(this.priceListDetails.priceListLines.map(item => ...

I am looking to modify the ID of the select element nested within a td tag

This is the code snippet I am working with: <tr> <td class="demo"> <label>nemo#2 Gender</label> <select id="custG2" required="required"> <option>....</option> <option>M</option> ...

Navigating Parse object attributes within AngularJS

Currently, I am in the process of developing an AngularJS application that utilizes data from a parse-server backend. To retrieve this data, I use services that are called from my controllers. However, as Parse objects require all properties to be accessed ...

Triggering the body onunload event

I am currently developing a HTA that needs to make final modifications on the onunload event. However, I am facing an issue as the event does not appear to be triggered. Can someone confirm if this event is still supported? Is there an equivalent event in ...

Troubleshooting issues with AngularJS routing

Having trouble clicking on the show button and seeing anything displayed. I've spent a lot of time on this without success, can someone please assist. Files.... app.js controller.js index.html show.html index.html <html ng-app='Java4sApp& ...

What is the best way to transfer the value of a <span> element to a different <div> using jQuery or JavaScript

Is there a way to move or copy the price and insert it into the <div class="info"> using jQuery? The code I'm currently using is returning an unexpected result of "102030". jQuery(document).ready(function($) { $(document).ready ...

What's the best way to modify the style property of a button when it's clicked in

I am working with a react element that I need to hide when a button is clicked. The styles for the element are set in the constructor like this: constructor(props) { super(props); this.state = { display: 'block' }; this. ...

Query the Mongoose database to fetch all records that are not listed in the array field of the same collection

I am facing a challenge with my Post schema. Within this schema, there is an array field that can contain other posts as replies. My goal is to retrieve all the documents that are not referenced in any post's replies field. Essentially, I want to extr ...

Having trouble retrieving a variable by POST in the backend through AJAX, yet it works perfectly fine in the frontend

Hey there! I'm facing an issue that I'm hoping someone can help me with. I'm attempting to send a tag attribute, stored in a JavaScript variable, to the backend (PHP) via AJAX. $.ajax({ type: "POST", url: '/requests/mercury.php ...

Strip away double quotation marks from object attributes except those beginning with a number

I've searched extensively and reviewed various Q&A forums, but I haven't encountered a scenario quite like this. Here's an example of the object I'm working with: props: { "label": "1rem", "text3": "1rem", "text2Button": "1re ...

Encountering a "Vue is not defined" error in Laravel 5.8 while constructing a comment system using Vue.js

I'm struggling to implement a comment system using Vue.js in my Laravel project. Despite my efforts, I keep encountering a "Vue not defined" error in the console. Can anyone shed some light on why this might be happening? Below is the code snippet I&a ...

Avoid assigning a class name to child elements if both the parent and child elements already have inline background colors

I have a challenge where I need to assign a random class name to elements that have an inline background color. The additional condition is that if both the parent and child elements have inline background colors, the child element should not receive the c ...

On smaller screens, the top placement of right sidebar links is necessary

Our website layout is organized into 3 main sections: the top part contains the main menu, followed by the main content and a sidebar specific to each page. The main content and sidebar are structured using bootstrap col-* classes. On small screens, I en ...

The inputmask is triggering an unhandled RangeError due to surpassing the maximum call stack size

I need to dynamically set a regex pattern on the idnumber field by selecting a different value from the idtype dropdown. Everything works smoothly until I choose the last option which contains a "?" character, causing the page to become unresponsive and di ...