Order of Execution

I am facing an issue with the order of execution while trying to retrieve values from my WebApi for input validation. It appears that the asynchronous nature of the get operation is causing this discrepancy in execution order.

I believe the asynchronous behavior is the cause, but I'm unsure how to resolve it. Can you offer any assistance?

See the example below for reference:

Code:

if (ano.length == 4 && ano > 1900 && ano < 2100) {
    // Checking the allowed range for month and day values
    if (dia > 0 && dia <= 31 && mes > 0 && mes <= 12) {
        // Verifies months with 30 days  
        if ((mes == 4 || mes == 6 || mes == 9 || mes == 11) && dia > 30) {

            return { 'dataValidation': 'data is invalid.' };
        }
        // handles February for leap years
        if (mes == 2) {
            // checks for leap year
            if (ano % 4 == 0 && (ano % 100 != 0 || ano % 400 == 0)) {
                // Maximum 29 days for February in a leap year   
                if (dia > 29)
                    return { 'dataValidation': 'data is invalid.' };
            } else if (dia > 28) {

                return { 'dataValidation': 'data is invalid.' };
            }
        }
    } else {

        return { 'dataValidation': 'data is invalid.' };
    }

    // 3rd step
    this.filiadoService.validarIdadeFiliacao(c.value).subscribe(
        data => {
            this.dataNascimentoModel = data;
        });

    //2nd step
    if (!this.dataNascimentoModel.IsValido) {
        return { 'dataValidation': 'data is invalid.' };
    } else {
        return null;
    }

Answer №1

Indeed, the asynchronous nature of http calls is causing this issue. Luckily, fixing it is quite simple! Just ensure that the logic intended to execute after the http call is moved inside the subscribe callback.

However, keep in mind that you can no longer return values directly from within the subscribe callback. Instead, pass your own callback function as a method parameter where you provide the object as an argument (e.g.,

callback({ 'dataValidation': 'data is invalid.' })
)

methodName(..., callback: (validationObject) => void) : void {
    if (ano.length == 4 && ano > 1900 && ano < 2100) {
        // Checking the allowed range for months and days
        if (dia > 0 && dia <= 31 && mes > 0 && mes <= 12) {
            // Verify the months with 30 days  
            if ((mes == 4 || mes == 6 || mes == 9 || mes == 11) && dia > 30) {

                callback({ 'dataValidation': 'data is invalid.' });
                return;
            }
            // If month is 2, check for leap year
            if (mes == 2) {
                // Leap Year condition
                if (ano % 4 == 0 && (ano % 100 != 0 || ano % 400 == 0)) {
                    // Maximum day for February in a leap year is 29
                    if (dia > 29)
                        callback({ 'dataValidation': 'data is invalid.' });
                        return;
                    // Maximum day for February in non-leap years is 28                  
                } else if (dia > 28) {

                    callback({ 'dataValidation': 'data is invalid.' });
                    return;
                }
            }
        } else {
            callback({ 'dataValidation': 'data is invalid.' });
            return;
        }

        // Validate age affiliation
        this.filiadoService.validarIdadeFiliacao(c.value).subscribe(
            data => {
                this.dataNascimentoModel = data;

                if (!this.dataNascimentoModel.IsValido) {
                    callback({ 'dataValidation': 'data is invalid.' });
                } else {
                    callback(null);
                }
            }
        );
    }
}

To invoke the method:

methodName(..., (data) => {
    if (!data) {
        console.log("data is valid");
    }
    else {
        console.log(data.dataValidation);
    }
});

Answer №2

Appreciate your response! I managed to solve the issue by importing the NG_ASYNC_VALIDATORS and utilizing Promises.

return new Promise(resolve =>
            this.filiadoService.validateFiliationAge(c.value).subscribe(res => {
                if (res.IsValido == true) {
                    resolve(null);
                }
                else {
                    resolve({ 'dataValidation': 'data is invalid.' });
                }
            }));

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

Choosing an option from the dropdown menu with the help of the incredible HTMX framework

I attempted the provided solution but unfortunately, it did not yield the desired outcome. Upon checking the HTMX log, it appears that everything is set up correctly. Can anyone point out what mistake I might be making in this scenario? document.getElem ...

Issues encountered while transitioning from Angular 2 to 4 using npm

I am facing a challenge in upgrading Angular 2 to Angular 4 using npm. I have tried running "npm update --save" in the terminal, but unfortunately, my package.json does not reflect the latest Angular 4 version and remains unchanged. Can someone please ad ...

Securing pathways and pages using NextJs

I recently completed a project where I implemented route protection for a website using the if and else statements, assigning each page a function withAuth(). However, I have concerns about whether this is the most effective method for securing routes in n ...

Struggling to locate images in Three.js

I'm facing a challenge with my Vue Cli app where I am attempting to use Three.js for rendering 3D objects within it. The issue arises when I attempt to load an image to utilize as a texture. let scene = new Three.Scene(); const spaceTexture = new Th ...

Incorporating Bootstrap 3 into an Angular 2 Application with Webpack

My Angular 2 project is utilizing the Webpack module bundler and I am looking to incorporate Bootstrap into the application using webpack. Bootstrap has been installed via npm, as reflected in my package.json file: "devDependencies": { "@angular/co ...

Looking to obtain rendered tree data upon page load?

Is there a way to retrieve all rendered tree metadata when the page loads using jstree? I'm looking for an output similar to this: [23,24] Please note that I would like to have each id stored in the metadata object displayed as [23,24] upon page loa ...

Disable javascript when using an iPad

I'm working on a website with parallax scrolling that I don't want to function on iPads. Is there a way to prevent the parallax effect from happening when the site is accessed on an iPad? Any guidance on how to disable parallax scrolling based o ...

Enhance component error handling in Angular 6 with customized updates

I am currently utilizing Angular 6. To manage network errors effectively, I have devised a customized Error Handler that extends ErrorHandler. import {ErrorHandler, Injectable, Injector} from '@angular/core'; import {HttpErrorResponse} from &a ...

Tips on adjusting the label on a datetime-local button

While using mobile browsers, I noticed that the datetime local feature includes three buttons. One of these buttons is called the Set button, but I would like to change its name to Ok. Is there a way to do this? I tried looking for solutions but couldn&apo ...

Utilizing Bootstrap to allow for seamless text wrapping around a text input field

I am trying to implement a "fill-in-the-blank" feature using Bootstrap, where users need to enter a missing word to complete a sentence. Is there a way to align the text input horizontally and have the rest of the sentence wrap around it? This is my curr ...

Variety of part ingredients

In my component, I have a button and include another component which also contains a button. How can I align these two buttons next to each other without using absolute positioning? When I try positioning them using absolute right and top values, the lay ...

The browser encountered an issue trying to load a resource from a directory with multiple nested levels

I've stumbled upon an unusual issue. Here is a snapshot from the inspector tools. The browser is unable to load certain resources even though they do exist. When I try to access the URL in another tab, the resource loads successfully. URLs in the i ...

Utilize Vue.js to selectively display or manipulate objects with a

I am currently working on a Vue.js component page that receives data from my backend. The page consists of three different filters/states that users can choose from: Unlabeled, Completed, and Skipped. Unlablled Completed Skipped My approach involves usin ...

Send the user back to the previous page once authentication is complete

I am integrating Google authentication through Passport in my web application and I am facing an issue with redirecting the user back to the original page they requested after a successful sign-in. It seems like the use of location.reload() might be causin ...

Struggling to update TypeScript and encountering the error message "Unable to establish the authenticity of host 'github.com (192.30.253.113)'"

While attempting to update my version of TypeScript using npm, I ran into an issue when trying to execute the following command: localhost:Pastebin davea$ npm install typescript/2.8.4 --save-dev The authenticity of host 'github.com (192.30.253.113)&a ...

Ways to automatically include a local variable in all functions

In each of my functions, I start with this specific line: var local = {} By doing so, it allows me to organize my variables using the following structure: local.x = 1 local.y = 2 Is there a way to modify all function prototypes to automatically include ...

How can I incorporate dynamic data to draw and showcase graphs on my website using PHP?

I am currently working on a project that requires displaying a graph showing the profit of users per day. Currently, I have implemented code to display a static graph on my page. <script type="text/javascript" src="https://www.google.com/jsapi">< ...

JWPlayer encounters an issue: "undefined" function is not defined

Can anyone lend a hand with this issue I'm facing? I'm attempting to upload a video using jwplayer but encountering errors. Here is the snippet of code I'm utilizing: <script type="text/javascript"> jwplayer("leg ...

Creating a dynamic input box that appears when another input box is being filled

I have a form set up like this: <FORM method="post"> <TABLE> <TR> <TD>Username</TD> <TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD> </TR> <TR> <TD>A ...

Contrasting .queue() with jquery.queue()

Can someone clarify the distinction between .queue() with .dequeue() and $.queue() OR jquery.queue()? If they serve the same purpose, why did jQuery provide them in two separate documentations? Could someone provide examples to illustrate their difference ...