Angular firing a function in the then clause before the initial function is executed

I have a situation where I need to make multiple service calls simultaneously, but there is one call that must be completed before the others are triggered. I have set it up so that the other calls should only happen after the .then(function() {}) block of the initial call. However, upon checking Chrome Dev Tools and observing an SQL error, it seems like all the calls in the subsequent then clause are firing off earlier than expected. What could be causing this issue?

        var promises = [];

        if (this.partner.customerId > 0) {
            if (this.isDirty('ipn.individualPartnerName')) {
                promises.push(this.partnerEditService.updateIndividualName(<Interfaces.IIndividualPartner>this.partner));
            }

            if (this.isDirty('bpa.mailingAddressForm') || this.isDirty('bpa.streetAddressForm')) {
                promises.push(this.partnerEditService.updateAddresses(this.partner));
            }

            if (this.isDirty('bn.businessName')) {
                promises.push(this.partnerEditService.updateBusinessName(<Interfaces.IBusinessPartner>this.partner));
            }

            if (this.isDirty('rc.individualPartnerResponsibilities') || this.isDirty('rc.businessPartnerResponsibilities')) {
                promises.push(this.partnerEditService.updateResponsibilities(this.operation, this.partner));
            }
        }

        this.partnerAddRepository.addExisting(this.operation.operationId, this.partner.customerId)
            .then(() => {
                this.executeSaves(promises);
            });


    executeSaves = (promises) => {
        this.$q.all(promises)
            .finally(() => {
                this.$mdDialog.hide(this.partner);
            });
    }

Here is the partnerAddRepo.addExisting function:

    addExisting = (operationId: number, partnerId: number) => {
        return this.$http.put(`my/path/to/operation/${operationId}/partner/${partnerId}`);
    };

It seems that the service calls within the executeSaves, which include the 4 different calls, are being executed before the partnerAddRepository.addExisting call is made. Why might this be happening?

Answer №1

When you make service calls, they are immediately executed upon calling them. Promises defer the return value of the function call, not the actual execution of the function.

If your intention is to invoke another function only after partnerAddRepository.addExisting has returned a value, then you should create an array of promises within the then callback.

this.partnerAddRepository.addExisting(this.operation.operationId, this.partner.customerId)
    .then(() => {
        var promises = [];

        if (this.partner.customerId > 0) {
            if (this.isDirty('ipn.individualPartnerName')) {
                promises.push(this.partnerEditService.updateIndividualName(<Interfaces.IIndividualPartner>this.partner));
            }

            if (this.isDirty('bpa.mailingAddressForm') || this.isDirty('bpa.streetAddressForm')) {
                promises.push(this.partnerEditService.updateAddresses(this.partner));
            }

            if (this.isDirty('bn.businessName')) {
                promises.push(this.partnerEditService.updateBusinessName(<Interfaces.IBusinessPartner>this.partner));
            }

            if (this.isDirty('rc.individualPartnerResponsibilities') || this.isDirty('rc.businessPartnerResponsibilities')) {
                promises.push(this.partnerEditService.updateResponsibilities(this.operation, this.partner));
            }
        }

        this.executeSaves(promises);
});

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

Encountering difficulties in sending a JavaScript array through jQuery ajax request

I'm feeling hesitant to ask this, but I can't figure out why my code isn't working. Here's what I have: <script> var formArray = new Array(); formArray['start'] = "one"; formArray['stopat'] = "two"; formArray ...

Can you explain the meaning of <T = MyType>?

While exploring a TypeScript file, I stumbled upon this interface declaration: interface SelectProps<T = SelectValue> extends AbstractSelectProps { /* ... */ } I've searched through the TypeScript handbook for <T = but couldn't find an ...

Guide on how to display matching options in an input box using HTML datalist based on user input at the beginning

I am a beginner in React and I am looking to create an autocomplete suggestion box for a text input field. I want the suggestions to only match the first letters of the available options, unlike the current behavior of HTML's <datalist>. Althou ...

When aggregating data using Mongoose expressions, Number, Boolean, and ObjectId types are not compatible

I am facing an issue with my query: const match: PipelineStage.Match = { $match: { deleted: false, provinceId: new mongoose.Types.ObjectId(req.params.provinceId), }, }; const query: PipelineStage[] = [match]; const c ...

Guide to sending post variables in an AngularJS service

Is there a way to send POST variables to a RESTful API using an angularjs service? I currently have the following setup: angularjsServices.factory('LoginService', [ '$resource', function($resource){ return function(user, pass){ ...

Using a for loop, how can the property value be set in another object?

One challenge that I am facing is setting object property values. The object in question looks like this: const newPlan = { name: '', description: '', number: '', monday: { breakfast: '', ...

Refreshing the data source on a DevExtreme menu is a simple process that can be

Utilizing the angular-translate library for internationalization has its quirks, mainly because the $translate service loads strings asynchronously. Below is a snippet of code from a controller where I need to replace the current datasource items with a n ...

Exploring JavaScript and accessing objects

I'm currently working on a small file-manager project in JavaScript and I've encountered an issue with the code. In the `get()` function, I am trying to access the `Content.files` array but it seems like there's some problem with variable sc ...

While executing a for loop, the variable $.ajax is found to be null in Javascript

When I click on a button with the function btn-book, there is a for loop inside it that fetches data from Ajax. Despite knowing that the data holds values, I constantly receive null. Below is the code snippet for the onclick event: $('#mapContainer&a ...

What is the best way to transfer functions connected to an Object over to Object.prototype?

Imagine having this: var exampleObject = {age: 25, name: 'John'}; If you do this: Object.keys(exampleObject); // it will return ['age', 'name'] Now, what if you want to add this functionality to the object prototype? You c ...

Subscribe on Footer triggers automatic scrolling to the bottom of the page

Whenever I fill out the form in the footer and hit submit, it directs me to a different page while automatically scrolling back down to the footer. I'm looking for a solution that prevents this automatic scrolling. I've attempted using window.sc ...

Ways to resolve the issue with the information window on Google Maps

I have a problem with displaying infowindows in Google Maps; currently, it only shows the information for the last marker added. let myLatlng = new window.google.maps.LatLng(-33.890542, 151.274856 ); let mapOptions = { zoom: 13, cent ...

Troubleshooting an Issue with MediaStreamRecorder in TypeScript: Dealing with

I've been working on an audio recorder that utilizes the user's PC microphone, and everything seems to be functioning correctly. However, I've encountered an error when attempting to record the audio: audioHandler.ts:45 Uncaught TypeError ...

Execute environment validation on server during `next build` command

I have a src/config/server/ts file that contains the following code: 'use server'; import zod from 'zod'; if (typeof window !== 'undefined') { throw new Error('env should not be imported on the frontend!'); } co ...

Tips on redirecting a user to a specific page after they have made a selection without doing so immediately

I am a beginner in the world of coding. Currently, I am working on creating templates for an online software application. Users will have the option to select from different choices using radio buttons. However, I want to ensure that users are not redirect ...

Creating a background with image overlays in React: A step-by-step guide

My challenge is to have an image that covers the entire background but it seems to stop abruptly where another object is placed, unable to extend further. I am utilizing Material UI and here is a snippet of my code: import { Image } from "../images&q ...

Utilize a date state variable in JSX Text based on a specific condition

My goal is to create a feature that allows users to pick a date using DateTimePickerModal. I want to display a clickable message that says "Select date" before any date is chosen, and then replace it with the selected date. While I am not certain if there ...

Preventing the triggering of events or functions while utilizing angular-gantt

Currently, I am utilizing the Angular directive called angular-gantt to create a gantt chart that displays tasks. Among the various options available, the ones I am focusing on are on-row-clicked, on-task-clicked, and on-task-updated. The issue I am facin ...

Tips for managing errors when using .listen() in Express with Typescript

Currently in the process of transitioning my project to use Typescript. Previously, my code for launching Express in Node looked like this: server.listen(port, (error) => { if (error) throw error; console.info(`Ready on port ${port}`); }); However ...

Securing an AngularJS page with Spring Security is not achievable

I've implemented Spring Security to secure my application using the configuration below in an attempt to display the default Spring login page: spring-security.xml <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns: ...