Encountering challenges with synchronous calls in AngularJS

Two service calls need to be executed synchronously in a specific order, using promises. However, the execution is not happening as intended.

Controller:

vm.nominationSVC.zipping(vm.fileSelected, vm.selectedCategoryId).
            then(function (response: any) {   //Zipping
                vm.nominationSVC.downloadDocument("documents.zip");  
            }).
            then(function (response: any) {
                var deffered = vm.$q.defer();
                for (i = 0; i < vm.rowSelectedLength; i++) {
                    vm.objDownloadHistory.Nomination_Id = vm.nominationIdSelected[i];
                    vm.objDownloadHistory.FilePath = vm.fileNamesSelected[i];
                    vm.promises.push(vm.nominationSVC.updateDownloadHistory(vm.objDownloadHistory));
                }
               //  vm.$q.all(vm.promises).then(function () {
              //       console.log("sdsd");
             //   });
            }).
           then(function (response: any) {
         vm.getNomiantionList();
        });

The method vm.nominationSVC.updateDownloadHistory(vm.objDownloadHistory) does not execute fully and moves down to other .then method, vm.getNomiantionList();

Attempts have been made with $q.all as mentioned in commented code but the issue remains unresolved.

Service Method:

updateDownloadHistory(objDownloadHistory: SpotAward.DownloadHistory)
        {
        var vm = this;
        var url: any;

        var deferred = this.$q.defer();
        url = this.BaseUrl + 'DownloadHistory/UpdateDownload';
        if (url !== null) {
            this.$http.post(
                url,
                JSON.stringify(objDownloadHistory),
                {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }
            ).then(function (result: any) {
                if (result.data > 0)
                    deferred.resolve(result.data);
            }).catch((data) => {
                deferred.reject(data);
            });
        }


        return deferred.promise;
    }

Answer №1

As per the provided code, the expected behavior should be as follows: - Execution of vm.nominationSVC.zipping - Once the promise returned by vm.nominationSVC.zipping is resolved, the following three then() functions will be invoked sequentially. However, this approach is not considered a good practice.

It's recommended to use only one then() call per promise to maintain a clear chain of callbacks. You can try something like this:

vm.nominationSVC.zipping(vm.fileSelected, vm.selectedCategoryId).
        then(function (response: any) {   //Zipping
            vm.nominationSVC.downloadDocument("documents.zip");  

            var deferred = vm.$q.defer();
            var promises = [];
            for (i = 0; i < vm.rowSelectedLength; i++) {
                vm.objDownloadHistory.Nomination_Id =vm.nominationIdSelected[i];
                vm.objDownloadHistory.FilePath = vm.fileNamesSelected[i];
                promises.push(vm.nominationSVC.updateDownloadHistory(vm.objDownloadHistory));
            }

           $q.all(promises).then(function () {
                 vm.getNomiantionList();
           });
        });

In this revised version, the previous three then() calls will now execute in sequence (assuming vm.nominationSVC.downloadDocument is synchronous and does not return a promise).

I trust that this solution proves helpful.

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

Alter certain terms in HTML and update background using JavaScript

I want to create a filter that replaces inappropriate words and changes the background color using JavaScript. Here is what I have so far: $(document).ready(function () { $('body').html(function(i, v) { return v.replace(/bad/g, &apos ...

What could be causing me difficulty in integrating NProgress into my Next.js application?

Despite following all the necessary steps for implementing the nprogress package, I am facing an issue where the loading bar shows up when routes are changed but nprogress fails to function properly. I have attempted alternative ways such as linking the st ...

Do not consider file extensions when using child_process fork with node-dev and Typescript

In my Typescript project, I utilize both node-dev and ts-node in my local development environment. To create a subprocess, I make use of the fork method from child_process, as shown here: fork(path.join(__dirname, './worker.ts')); While this se ...

Issue with MVC framework: AJAX query callback function not functioning properly

Struggling with implementing a basic Jquery Ajax callback: Here is my Jquery code snippet: $(document).ready(function () { $('#btnClient').click(function (e) { e.preventDefault(); var txtClient1 = $('#txtCli ...

Show the MySQL query results in a pop-up alert box

I need assistance with querying a MySQL database for certain results using PHP and then displaying the result in an alert dialog box through JavaScript. I am able to connect to the database, query the data successfully, and display it on a PHP page. Howeve ...

Enhanced memory allocation for JavaScript clients

Creating a JavaScript script that demands significant amounts of RAM, possibly around 100MB. I need to generate a large array on the client-side. Is there an HTML tag available to allocate more memory for the script? Code: <html> <head> ...

Overseeing the management of JavaScript dependencies

Our website is plagued with old frontend code that's in disarray. It's a mishmash of different versions of JavaScript frameworks and libraries being loaded. Some parts of the code have messy inline JavaScript that attempts to handle dependencies ...

Reproducing scripts in Google Tag Manager and React/Next applications

Currently, I am delving into the realm of Google Tag Manager and React + Next.js for the first time. This experience is proving to be quite intriguing as my familiarity with GTM is limited and my exposure to React is even less. Nonetheless, it's not a ...

Encounter an Error: Received undefined or Promise { <pending> } while attempting to add an element to an array

Having issues adding to an array in a server-side rendered page using the code below. let categories = [] categories = await axios.get(`http:/.../${price_list_name}`).then(res => { return res.data }) const child_categories = ca ...

Use Angular.js to perform navigation after clicking the "Ok" button on a confirmation box

I encountered a problem with my requirement. I need a confirm box to appear when the user attempts to navigate to the next state/page. Only if the user clicks on the "Ok" button should it proceed to the next state; otherwise, it should stay as it is. Below ...

How to effectively use the LIKE statement in mysql with node.js

app.post('/like/:level/:name', function(req, res){ connection.query("SELECT * from books where " + req.params.level + " like '%" + req.params.name + "'%", function(err, rows, fields) { if (!err){ var row = rows; res.send(row); console.l ...

Angular5+ Error: Unable to retrieve summary for RouterOutlet directive due to illegal state

When attempting to build my Angular App using ng build --prod --aot, I consistently encounter the following error: ERROR in : Illegal state: Could not load the summary for directive RouterOutlet in C:/Path-To-Project/node_modules/@angular/Router/router.d. ...

What is the method to override a meta tag?

My website is currently hosted in a very strange place. Recently, they inserted this code into the "Head" section of my web pages: <meta name="robots" content="noindex, nofollow, noarchive"> Unfortunately, I am unable to directly ...

Mastering the art of combining style with the perfect class name

I am looking to update all instances of <p class="p1"><span class="s1"> Sent with the appropriate style that was defined earlier in my iOS project. I am relatively new to iOS development and this is a dynamic HTML content that can render in v ...

Display and conceal individual divs using jQuery

Despite my lack of experience with jQuery, I am struggling with even the simplest tasks. The goal is to display/hide specific messages when certain icons are clicked. Here is the HTML code: <div class="container"> <div class="r ...

Show the interface value for an array type

I have created a component to display API data. The structure of the component is as follows: HTML: <div *ngFor="let customer of customers"> <p>Name: {{customer?.name}}</p <p>Phone: {{customer?.phoneNumbers}}</p </div&g ...

Using the feColorMatrix SVG filter in CSS versus applying it in JavaScript yields varied outcomes

If we want to apply an SVG filter on a canvas element, there are different ways to achieve this. According to this resource, we can apply a SVG filter to the CanvasRenderingContext2D in javascript using the following code snippet: ctx.filter = "url(#b ...

Setting up a web server with a cyclical challenge

I've encountered an issue while hosting my server.js file with the configured API on Cyclic. The deployment was successful, but every endpoint call is returning a status 500 error. Additionally, I have hosted the React front-end on github pages. I&apo ...

Troubleshooting the issues with testing AngularJS using Jasmine and Karma, particularly when $httpBackend is

I'm currently in the process of writing unit tests for my Angular app using Jasmine with Karma. One of the functionalities of the app is to make a call to the GitHub API, retrieve a user's repository names, and store them in an array. Although I& ...

How can I verify that the value entered in an input field matches a specific date format such as "MM/dd/YYYY" using Angular?

I need to validate if a given value matches a specific date format such as "MM/dd/YYYY." Typescript file onValChange(event: Date) { const datePipe = new DatePipe('en-US'); const val = datePipe.transform(event, 'MM/dd/yyyy'); ...