Iterating through a series of AJAX requests in JavaScript until the variable equals "No" and then terminating the loop

After dedicating the past two days to my work, I am still struggling to find a solution. Any assistance would be greatly appreciated. My current setup involves nodejs and Vue.

  • I need help figuring out how to break out of an AJAX call when receiving a "No" result and stop the loop.
  • I am encountering issues accessing the userExist array variable.
  • The same problem arises when trying to work with the this.info['isthisUser'] Vue variable.
var thisUser = ["NY","NJ","CT","CA"]

var userExist = mycheck(thisUser)
console.log(userExist);

this.info['isthisUser'] = userExist;
console.log(this.info['isthisUser']);    

function mycheck(val) { 
    var usCNT = val.length; 
    var array = new Array();

    if (usCNT>0) {
        for (var u=0; u<usCNT; u++) {
        var checkThisUser = val[u];
            $.ajax
            ({
            type: "POST",
            url: '/getStates',
            data: { user: checkThisUser,},
            success: function (data, msg) {
            result = data ; 
            array.push(result);
            if(result === 'No') {
                alert('not exist');
                }
            })
        }
    }   
    return array;
};

console.log(userExist) displays the following format:

[]
0: "No"
1: "No"
2: "No"
3: "Yes"
length: 4
__ob__: Observer {value: Array(4), dep: Dep, vmCount: 0}
__proto__: Array

console.log(this.info['isthisUser'])
shows the below:

[__ob__: Observer]
0: "No"
1: "No"
2: "No"
3: "Yes"
length: 4
__ob__: Observer {value: Array(4), dep: Dep, vmCount: 0}
__proto__: Array

Answer №1

This code is outdated, and remember that $.ajax requests are executed simultaneously, so stopping a loop early will not stop them from completing unless they are specifically aborted.

If you need the requests to run one after another, you can use async..await. The $.ajax function can return a promise:

async function mycheck(val) { 
    ...
    var array = [];
    for (var u=0; u<usCNT; u++) {
        var result = await $.ajax({
          type: "POST",
          url: '/getStates',
          data: { user: checkThisUser,}
        });
        if (result === 'No') {
            throw new Error('not exist');
        }
        array.push(result);
    }
    return array;
};

Using promises requires consistent usage with either async..await or plain then and catch. Since mycheck can return a rejected promise on throw, errors must be handled by the caller.

If the goal of this function is to return a boolean value, it can be simplified as follows:

    ...
    for (var u=0; u<usCNT; u++) {
        var result = await $.ajax({
          type: "POST",
          url: '/getStates',
          data: { user: checkThisUser,}
        });
        if (result === 'No') {
           return false;
        }
    }
    return true;

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

Ways to apply the margin-top property to create space between an input field and

I have been experimenting with Vue and I created a simple code snippet. <template> <div> <input /> <span class="span-text">Hi</span> </div> </template> // index.css .span{ margin-top: 3px; } I a ...

Experiencing issues with passwords in nodemailer and node

Currently, I am utilizing nodemailer in conjunction with Gmail and facing a dilemma regarding the inclusion of my password. The predicament stems from the fact that my password contains both single and double quotes, for example: my"annoying'password. ...

What could be causing my issue with the if-else condition not functioning properly?

Why does the code only work for adding and removing styles in Part (else), but not returning the class when clicked again? var navDropDown = document.querySelectorAll('.menu-item-has-children > a'); for (let i = 0; i < navDropDown.length; i ...

Creating a layout of <video> components in vue.js, complete with the ability to rearrange and resize them through drag and drop functionality

Despite trying numerous libraries and Vue.js plugins, I have yet to find one that meets all of my requirements. I am in need of creating a grid of video HTML elements that are draggable and resizable with a consistent aspect ratio of 16:9. Additionally, I ...

Creating a nested list of objects in JavaScript can be achieved by using arrays within objects

I'm currently in the process of creating a new Product instance in Javascript, with the intention of sending it to the server using [webmethod]. [WebMethod] public static void SetProduct(Product product) { // I need the Product instance ...

Establishing Redux States within the Provider (error: Provider encountering useMemo issue)

Exploring redux for state management has been a new journey for me. I am hoping it will help reduce API calls and increase speed, but I've hit a roadblock with an error that I can't seem to figure out. To troubleshoot, I created a simplified vers ...

What's the best way to manage endless routing options in express.js?

After reviewing the topic of handling routes in Express.js on Stack Overflow, I came across the following example : var express = require("express"); var app = express(); app.get("/", function(request, response) { response.send(&quo ...

Click to expand for answers to commonly asked questions

Having trouble setting up a FAQs page on my blog and can't seem to get the code right. Check out what I'm trying to do here: http://jsfiddle.net/qwL33/ Everything seems fine but when I click on the first question, both questions open up. Can som ...

Passing data from an API in Vue.js to a different page

I'm a beginner with Vue Js and I'm looking for guidance on how to send data between two components. Currently, I am working on a Vue app that fetches a list of users from an API and displays them. My goal is to transfer data between these compone ...

Cross-domain scripting

I have a unique javascript code hosted on my server. I want to offer website visitors a similar implementation approach to Google Analytics where they can easily embed the script on their servers. For instance: <script type="text/javascript" src="http: ...

Guide to filling a Vuetify v-file-input with pre-set text contents?

How can we display the file name in the v-file-input component in an edit screen to indicate that a file has already been uploaded by the user? Previous attempts to achieve this feature include: Setting the v-model to the file name (but the name does not ...

Leveraging a personalized Vue directive alongside Inertia.js

Working on a Laravel app with Inertia.js and Vue 3, I want to incorporate a custom Vue directive that I created in a previous project not utilizing Inertia. Here's what I tried in my app.js: app.directive('uppercase',{ updated(el){ ...

What could be causing the shake effect on the MUI dialog to not work when clicking away?

I am trying to implement a shake effect when the user clicks outside the MUI dialog to indicate that clicking away is not allowed. However, the code I have so far does not seem to be working as the effect is not being applied. Can someone please help me ...

Refreshing specific iframes without having to reload the entire webpage using jQuery

As the page loads initially, a hidden iframe and other visible ones are present. When a button is clicked, one of the visible iframes needs to be hidden while another becomes visible (with its src attribute set accordingly). The goal is to achieve this wit ...

Several adhesive panels on a dynamic webpage

In the content area of my page, a dynamic number of rows are generated. Each row consists of two columns: a side block and a content area. The goal is to have the side block stick while the page scrolls down until the next block appears and pushes the prev ...

The built-in functions of Wordpress are not able to be identified in the ajax PHP file

As a newcomer to Wordpress development, I am facing challenges with implementing ajax on my WordPress site. I am currently working on a plugin that requires the use of ajax. However, my php file (xxxecommerce.ajax.php) is not recognizing the built-in Word ...

Express npm dependency fails to start globally

I have recently reinstalled my operating system from Windows 8.1 to Windows 8.1, and I have been using npm for quite some time. Previously, it was working fine as mentioned here. After the reinstallation, I tried installing npm i -g express, but it does n ...

What could be causing the malfunction of the map function, despite the code appearing to be correct?

I have encountered an issue in my React functional component where I am trying to display a list of notifications. The useEffect() function is being called to generate the "data" which should then be displayed on the page. The code seems to be running fine ...

Implementing Skeleton Loading Animation for VueJS Components during Firebase Data Retrieval

Considering implementing a skeleton loading component to display while waiting for data to load from firestore. The code snippet below shows my attempt at using suspense to fallback, but it seems to not work with the firebase API. Here is a portion of my t ...

"Using the check function in JavaScript to determine if a value

I have a JSON file containing data, and I am looking to create a function that extracts only the values from each object and adds them to a list. Is there a more efficient way to write this code so it can run indefinitely and continue pushing non-object v ...