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

Is the JSON data missing from the POST request?

I'm having trouble inserting data into the database using a POST request. Here is how I'm making the request: 127.0.0.1:3000/api/users?fname=asd&lname=edc&<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d7870 ...

Command handler that dynamically utilizes both shared and separate commands

Currently, I am in the process of setting up a command handler for multiple channels on Twitch. To organize the commands, I have them divided into specific folders for each user and generic ones. Accessing these commands is done by using a map(). My goal i ...

Angular's Reactive forms: The power of bidirectional binding

Struggling with Reactive forms? I've encountered an issue where updating the model class when a User changes the input is easy, but what about programmatically changing the model and reflecting those changes in the HTML form? In simplified terms: th ...

Error: Jquery unrecognized - syntax issue

How can I properly add or remove the active class from an element based on a data-filter attribute in jQuery? When I attempt to do this, I receive the following error message:Uncaught Error: Syntax error, unrecognized expression: li[data-filter=.arroz-1] $ ...

Navigating pages with Jqueryor Using J

Currently, I am utilizing jQuery and AJAX to retrieve data from a remotely stored PHP file on a server. After successfully fetching the initial page and displaying the outcomes in an HTML table, I've encountered a new challenge. My goal now is to fetc ...

What could be causing the multifiles uploader to fail in uploading files?

I have been attempting to create a multiple files uploader with sorter connected to a database on my website. However, whenever I try to upload some files, the uploader sends me several notices. Notice: Undefined index: media in /var/www/mediasorter/mediau ...

What is the best way to ensure my dropdown menu closes whenever a user clicks anywhere on the page? (javascript)

I have created a dropdown that appears when the user clicks on the input field, but I would like to remove the active class so that the dropdown disappears if the user clicks anywhere else on the page. Here is my code snippet: // drop-down menu functi ...

State loss occurs when moving to a different page using next/link

Currently, I am working on a library application with Next.js. Within this project, there are two main pages: BooksPage, which displays a list of all books, and BookPage, where detailed information about a specific book is shown. The components involved in ...

Transclusive directives and nested components

Within my directive, I am binding a property like this: scope: {modelVar: "="} The directive template then uses this variable: <input ng-model="modelVar"> However, when I transclude this directive within another directive, the input lives in a ch ...

Injection of Angular state resolve into controller fails to occur

I'm attempting to ensure that the value from ui-router's resolve is successfully passed to the controller portalsForUserCtrl. Take a look at the router code below: (function () { 'use strict'; var myApp = angular.module("myApp", ["co ...

Negatives of utilizing two different UI libraries within a single react project?

I have been contemplating a decision that may be considered unconventional from a technical standpoint. Despite my search efforts, I have not come across any explanation regarding the potential drawbacks of this decision. Imagine creating a React website ...

Transforming a JavaScript array into a JSON format

Is there a way to convert a JavaScript array into JSON format? [{ "userName": "Rodrigo", "date": "April 25, 2017", "score": 5 }] [{ "userName": "Jon", "date": "April 24, 2016", "score": 4 }] Error: There is a parser error on line ...

Is there a solution to prevent the "NavigationDuplicated" error in Vue.js when adding query parameters to the URL without changing the path?

Presently, the URL shows /search The new URL should display /search?foo=bar I am looking to modify my query parameters on the current route after applying some filters on the page. This is my code: this.$router.push({query: params}) Although I can h ...

Extracting the value of an HTML element from a string variable in AngularJS

I am facing an issue with my application where the content of an HTML element is received as a template from the server. I am attempting to assign this template, which is essentially a string, and have the variables within the template linked to the contro ...

Developing a custom JavaScript function to iterate through a group of html elements

In my mission to create a function that loops through a set of HTML elements and gathers their values, I aim to then utilize those values to produce an HTML textarea. Thus far, I've established a series of HTML input boxes and a JavaScript function f ...

Cease the execution of promises as soon as one promise is resolved

Using ES6 promises, I have created a function that iterates over an array of links to search for an image and stops once one is found. In the implementation of this function, the promise with the fastest resolution is executed while others continue to run ...

What is the correct method for properly disposing of a Three.js Scene in version r55?

It appears that Three.js lacks a proper method for disposing of a THREE.Scene and all its contents. My current approach is as follows: $.each(scene.__objects, function(idx, obj) { scene.remove(obj); ...

"Unleashing the Glamour: Tips for Decorating an Amazing Ajax Pop

I need help styling a magnific pop-up that displays content from a uri. The content is just plain text and I want to avoid using any html code as the popup will be triggered by a button. The current code I have written functions correctly, but the appeara ...

Tips for transferring <form> information to an object array within a React application

I am currently working on a basic component that takes an input message, displays it in a list below the input field when submitted. However, I am facing an issue where clicking the submit button only results in a blank bullet point appearing below. impo ...

The icon on my page is not displaying, and the responsive menu is also not appearing

After tweaking the @media {} settings, I noticed that the icon displays properly when reduced, but disappears completely when fully covered with {}. Additionally, my responsive menu is not visible as expected. `@import url('https://fonts.googleap ...