Determining the completion of multiple asynchronous calls in AngularJS: A guide

I have a SQLService running on my PhoneGap/AngularJS app that processes a long array of Guidelines with DB transactions. How can I indicate when the final transaction is completed?

I envision a flow like this:

 In the controller, call `SQLService.ParseJSON`
    ParseJSON triggers `generateIntersectionSnippets`
      `generateIntersectionSnippets` makes multiple calls to `getKeywordInCategory``
        Trigger `.then` when the final call to getKeywordInCategory is completed
 SQLService.ParseJSON is finished, fire `.then`

I am struggling to manage the asynchronous calls. ParseJSON returns a promise resolved when generateIntersectionSnippets() finishes, but generateIntersectionSnippets() makes multiple calls to getKeywordInCategory, each returning promises.

Here is a simplified version of the issue:

I aim for $scope.ready = 2 to execute after all transactions are done. Currently, it executes after one iteration through generateIntersectionSnippets.

In the controller:

 SQLService.parseJSON().then(function(d) {
            console.log("finished parsing JSON")
            $scope.ready = 2;
            });

Service:

 .factory('SQLService', ['$q',
    function ($q) {

   function parseJSON() {
            var deferred = $q.defer();

                function generateIntersectionSnippets(guideline, index) {
                    var snippet_self, snippet_other;

                    for (var i = 0; i < guideline.intersections.length; i++) {


                            snippet_self = getKeywordInCategory(guideline.line_id, snippets.keyword).then(function() {
                                //Should something go here?
                            });

                            snippet_other = getKeywordInCategory(guideline.intersections[i].line_id, snippets.keyword).then(function() {
                                //Should something go here?
                            });

                        }


                    }

               deferred.resolve(); //Is fired before the transactions above are complete

            }

            generateIntersectionSnippets();

            return deferred.promise;

  } //End ParseJSON

  function getKeywordInCategory(keyword, category) {
            var deferred = $q.defer();

            var query = "SELECT category, id, chapter, header, snippet(guidelines, '<b>', '</b>', '...', '-1', '-24' ) AS snip FROM guidelines WHERE content MATCH '" + keyword + "' AND id='" + category + "';",
                results = [];

            db.transaction(function(transaction) {
                transaction.executeSql(query, [],
                    function(transaction, result) {
                        if (result != null && result.rows != null) {
                            for (var i = 0; i < result.rows.length; i++) {

                                var row = result.rows.item(i);
                                results.push(row);
                            }
                        }
                    },defaultErrorHandler);
                    deferred.resolve(responses);
            },defaultErrorHandler,defaultNullHandler);

            return deferred.promise;

        }




  return {
            parseJSON : parseJSON
        };
  }]);

I am seeking guidance on the correct approach for chaining promises across multiple asynchronous transactions. The current structure is flawed, and any assistance is appreciated.

Answer №1

Utilize the $q.all() method to synchronize the resolution of multiple promises.

function processJSON() {
    var deferred = $q.defer();
    var promiseArray = [];

    for (var index = 0; index < data.items.length; index++) {
        promiseArray.push(getData(data.items[index].id));
        promiseArray.push(getSecondaryData(data.items[index].id));
    }

    $q.all(promiseArray).then(function() {
        deferred.resolve();
    });

    return deferred.promise;

} //End ProcessJSON

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

"When attempting to pass a string into the res.send() method in Node.js, undefined

As a new Node.js user, I'm attempting to send data back to the browser by utilizing a function called load_blocks() from an external file that I created, and then calling it with res.send(). I currently have two basic files in my setup: The first on ...

Creating captchas seems like a mistake in reasoning to me

I am encountering an issue with my code. I created a basic newbie-level captcha using Javascript. Below is the code snippet: <!DOCTYPE html> <html> <head> <style> </style> </head> <body> <h1>T ...

Trouble uploading an audio blob as a base64 string using Google Drive API with the drive.files.create method - File ID could not be located

My current challenge involves sending an audio blob to a specific Google Drive folder. To accomplish this, I convert the blob into a file before initiating the transfer process. However, I have encountered an error from the beginning: Error: File not fo ...

What is the most effective method to prevent the auto-complete drop-down from repeating the same value multiple times?

My search form utilizes AJAX to query the database for similar results as the user types, displaying them in a datalist. However, I encountered an issue where it would keep appending matches that had already been found. For example: User types: "d" Datali ...

Updating the selection without refreshing the page

Whenever I change the value, my page refreshes because I need to send the value to query data. However, my selector does not display the value when selected. <form name='active' action='' method='GET'> <select class= ...

Obtain the AJAX response in separate div elements depending on whether it is successful or an error

Currently, my jQuery script outputs the result in the same div for error or success messages: HTML <div id="error-message").html(res); JQUERY jQuery('#register-me').on('click',function(){ $("#myform").hide(); jQuery ...

Determine the distinct elements in an array using JavaScript/jQuery

I have incorporated Gridster widgets into my webpage, each with a button that turns the widget's color to red when clicked. Upon clicking the button, the parent element is also added to an array. My main goal I aim to have the parent element added t ...

The Sluggishness of MongoDB Aggregation in Determining Distinct IDs within Retrieved Documents

Not only does my Mongo view return a filtered set of documents to the end user, but it also runs a couple of functions to calculate running totals. Strangely though, while my find() operation is blazingly fast (225ms), this additional aggregation process t ...

Securely authenticate with Node.js using screen scraping techniques

Attempting to scrape a website with authentication in node.js, but encountering an issue when trying to submit the form: "Your browser "for others" does not support our site." The username is being set, but the password field appears to be empty. Curren ...

Twice the data fetching through ajax on popup is observed using php mysql

I've been struggling for the past two hours. Attempted : location.reload(); reset form Tried many features, but after closing my popup and reopening it or opening another ID, the previous ID data is still visible. This happens continuously for all ...

Regular expression for textarea validation

I'm currently working on creating a regex for a textarea in my Angular 8 application. The goal is to allow all characters but not permit an empty character at the start. I've experimented with 3 different regex patterns, each presenting its own s ...

Tips for creating a smooth transition effect using CSS/JavaScript pop-ups?

Looking for some assistance in creating a CSS pop-up with a touch of JavaScript magic. I've managed to trigger the pop-up box by clicking a link, and while it's visible, the background fades to grey. But I'm struggling to make the pop-up fad ...

Encountering problem with JSON in the bodyParser function

I've encountered an issue while sending data from my React component using the Fetch API and receiving it as JSON on my Express server. When I try to parse the data using the jsonParser method from bodyParser, I only get back an empty object. Strangel ...

Using jQuery Datatables: Storing the received JSON data into a variable

I have incorporated 2 plugins for my project: Datatables (used for pagination) Defiant.js (providing JSON search capability) Describing my issue along with the code snippet... $(document).ready(function() { var myjson; //Initializing Datatable ...

Steps for incorporating an npm module

Recently, I created an npm package named "sum" with just a main.js file: export function sum (a , b){ return a+b } Here's how my package.json looks like: { "name":"sum", "version":"1.0.0", "description ...

What is the solution for excluding 0s in my javascript code?

I am working on a code to calculate the average of four numbers entered by the user, but I want to exclude zeros from the calculation. Currently, the code successfully excludes one zero, but I am struggling to exclude multiple zeros. My initial approach ...

Issue with updating state in Python Flask Angular application

I'm currently developing an application using Flask, Angular, and MongoDB. I've implemented state provider in Angular, and everything is loading correctly within the application. However, upon refreshing the page, a 404 error is being thrown. A ...

Content within innerHTML not appearing on the screen

I'm facing an issue with displaying an error message when the user enters incorrect username or password. The message should pop up below the sign-in box, but it's not showing up for some reason. Can anyone help me figure out why? Here is my cod ...

What could be causing my HTML5 page to crash when accessed online, but not when viewed locally?

I am just getting started with HTML5 and decided to experiment with canvas. This is the first canvas page I have created. Everything works fine when I run the page locally (i.e. file:///), but once I upload the files to my webhost, the page gets stuck whi ...

Dealing with JSON Stringify and parsing errors in AJAX

I've been troubleshooting this issue for hours, trying various suggestions found online, but I'm still encountering a problem. Whenever I encode function parameters using JSON.stringify and send them to my PHP handler through AJAX, I receive a pa ...