Tips for managing asynchronous code that invokes other asynchronous code in AngularJs

My factory utilizes indexedDB and a method called getRecipe that relies on this indexed db to fetch data.

The issue arises because indexedDB returns its instance in an asynchronous call, and getRecipe is another method that also returns its value asynchronously.

I attempted to tackle this using promises but unfortunately, I was unsuccessful.

app.factory('RecipesStorage', ['$q', function($q) { 
var getDb = function () {
   var deferred = $q.defer();

   var db;
   var request = indexedDB.open('recipes', 1);

   request.onupgradeneeded = function (e) {
       console.log('Upgrading indexedDb');
       var thisDb = e.target.result;

       if (!thisDb.objectStoreNames.contains('recipe')) {
           thisDb.createObjectStore('recipe');
       }
   }

   request.onsuccess = function (e) {
       db = e.target.result;
       window.db = db;
       deferred.resolve(db);
   }

   request.onerror = function (e) {
       console.error('Error when opening indexedDB');
   }

   return deferred.promise;
};

var getRecipe = function (recipeId, callback) {
        getDb().then(function(db) {
            var transaction = db.transaction(['recipe'], 'readonly');
            var objectStore = transaction.objectStore('recipe');

            var data = objectStore.get(recipeId);

            data.onsuccess = function (e) {
                var result = e.target.result;
                console.log('GetRecipe:', result);
                callback(result);
            }

            data.onerror = function (e) {
                console.error('Error retrieving data from indexedDB', e);
            }
        });
};

return {getRecipe:getRecipe};
}]);

However, the solution didn't work as expected. The function inside the then of getRecipe isn't triggered. I'm unsure about where the problem lies.

Answer №1

To achieve the desired result, we can employ a promise chain.

(In the absence of an actual database, I mimicked asynchronous responses and encapsulated the data using $q.)

See a demonstration on Fiddle

fessmodule.controller('fessCntrl', function ($scope, RecipesStorage) {

    $scope.alertSwap = function () {
       RecipesStorage.getDb()
                        .then(function (result) {
                           $scope.data = result;                           
                        }, function (result) {
                            alert("Error: No data returned");
                        });
    }

});

fessmodule.$inject = ['$scope', 'RecipesStorage'];

fessmodule.factory('RecipesStorage', ['$q', function ($q) {

    var getDb = function () {        
        var data = [{
            "PreAlertInventory": "5.000000",
            "SharesInInventory": "3.000000"
        } ];   
        var deferred = $q.defer();
        deferred.resolve(data);
        return getRecipe(data);        
    };

    var getRecipe = function(db){    
        var data = [{        
            "TotalSharesBought": "0.000000",
            "TotalShareCost": "0.000000",
            "EstimatedLosses": "0.000000"
        }]; 
        db.push(data[0]);
        var deferred = $q.defer();
        deferred.resolve(db);
        return deferred.promise;
    }

    var factory = {
        getDb: getDb
    };

    return factory;
}]);

Additional Information

  • By chaining promises together, you can structure code flows efficiently
  • Errors propagate within the chain, allowing for easy error handling at the end

Answer №2

Upon reviewing your code, I am unable to identify any issues. For further assistance, you may want to refer to this plunker which was created based on your code and seems to be functioning correctly.

Answer №3

The actual issue stemmed from the fact that I initially utilized Angular version 1.0.8 in my code, but once I upgraded to version 1.2.0, everything began functioning correctly. Much appreciated :)

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

struggling with managing an array of Vue3 refs

Having an issue with handling vue3 refs, specifically when retrieving data from Firestore. When logging the [documents], everything seems to work fine. However, I run into errors when trying to access values from an array within a document. For example, ...

Discover the process for breaking down JSON data into separate stages using the Express API

My API architecture is causing a problem as I try to insert it into an array called items[]. https://i.stack.imgur.com/qe802.png The setup involves a simple API built on express + mongodb. The challenge lies in figuring out how to store data from the pos ...

What methods can be used to accomplish this effect using CSS and/or Javascript?

Is there a way to achieve the desired effect using just a single line of text and CSS, instead of multiple heading tags and a CSS class like shown in the image below? Current Code : <h2 class="heading">Hi guys, How can i achieve this effect using j ...

Tips for assigning information from a react hook within a function or event

Currently, I am in the process of learning how to create hooks in order to efficiently reuse data that needs to be modified across different components. For my project, I am utilizing Material UI's Tabs and require the use of a custom hook called use ...

Utilizing attributes as scope properties within AngularJS

I am currently working on a directive and I need to pass the Attributes (Attrs) to the $scope, however, I am facing some difficulties in achieving this. Specifically, my goal is to assign attributes in my template based on the name set in my date-picker ta ...

What is the best way to outline the specifications for a component?

I am currently working on a TypeScript component. component @customElement("my-component") export class MyComponent extends LitElement { @property({type: String}) myProperty = "" render() { return html`<p>my-component& ...

Retrieving the selected date from mat-datepicker into a FormControl

When creating a POST request to an API, I encountered an issue with the mat-datepicker field as it throws an error when inside the ngOnInit() call (since nothing is selected yet). Other fields like name, email, etc. work fine, but extracting a value from t ...

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

Transforming a JSON object property value from an array into a string using JavaScript

I am facing an issue with an API call I am using, as it is sending objects with a single property that contains an array value (seen in the keys property in the response below). However, I need to work with nested arrays in order to utilize the outputted v ...

Oops! Looks like there was an error: weight is not defined when trying to calculate BMI with the HTMLButtonElement

I'm currently working on a project to create a BMI calculator following specific instructions. I've managed to follow all the guidelines except one regarding the letsCalculateBMI function. The instruction states: letsCalculateBMI should extrac ...

Leveraging conditional statements for dynamically computed Vue properties

In the Vue site I'm working on, there is a functional button that changes its state when clicked (from "pause" to "resume" and also changes colors). The button functionality itself works perfectly, but I am facing an issue in aligning it with another ...

Error: The current component does not have a template or render function specified. Check the <App>

I am a beginner in Vue js and I am facing an issue while running my application. It is showing an empty page with the error message: Component is missing template or render function. at <App>. Additionally, there is also a warning from Vue Router sa ...

Is there a resource available that can help me create a jquery/ajax image slider/carousel similar to this?

One thing that really caught my eye is how cnn.com has implemented this feature. I think it would be a great addition to the website I'm currently working on. I particularly like the page numbering, as well as the first, previous, next, and last butto ...

I need to see the image named tree.png

Could someone assist me in identifying the issue with this code that only displays the same image, tree.png, three times? var bankImages = ["troyano", "backup", "tree"]; jQuery.each( bankImages, function( i, val ) { $('#imagesCon ...

JQuery's .each method is executed prior to making an Ajax request

I am currently working on a JavaScript (jQuery) function that loops through input elements in a form, builds an array to convert into a JSON string, and then sends it to an AJAX endpoint. However, I am facing an issue where the loop runs after the AJAX cal ...

Include a stylesheet as a prop when rendering a functional component

Using Next.js, React, Styled JSX, and Postcss, I encountered an issue while trying to style an imported component for a specific page. Since the stylesheets are generated for a specific component at render time, I attempted to include custom styles for the ...

Can variables in JavaScript clash with input names in HTML?

I have the following code in an HTML file: <input type="..." name="myInput1" /> Then, in a JS file associated with this HTML file, I declare a variable to store the value of that input after it loses focus: var myInput1; Should I be concerned abo ...

The issue with Node module @kenjiuno/msgreader is that it is unable to find the constructor for MsgReader

I've been having trouble getting the example code for parsing Outlook .msg files using @kenjiuno/msgreader to work. Despite successfully installing the module with npm, my code doesn't seem to function as expected: const fs = require('fs&apo ...

Rearranging div placement based on the width of the screen

I am currently working on building a responsive website and I need two divs to switch positions depending on the screen width, both on initial load and when resizing. Despite my efforts in researching and trying various options, I have not been successful ...

Firefox Issue: SetTimeout Redirect Function Not Functioning Properly

Working on a page that redirects users to an installed application or a webpage as a fallback. This is implemented using ClientScript.RegisterStartupScript when the page loads, with a Javascript snippet like this: <script type='text/javascript&apo ...