1

I have been working for the last two days and struggling to find a solution. Would be helpful if someone helps me. I am using nodejs and Vue.

  • How should i come out from the ajax call when I get "No" result and need to stop the loop.
  • Not able to access the userExist array variable.
  • Also the same for when i converted to 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) shows this 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
Ivar
  • 6,138
  • 12
  • 49
  • 61
user3280899
  • 199
  • 2
  • 13
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ivar Oct 06 '20 at 14:47
  • Well you are making a bunch of asynchronous calls so all of them have been started.... loop os probably done before you are trying to cancel it. – epascarello Oct 06 '20 at 14:47
  • ajax is async. meaning all the calls have been made long before the response of one of them came back – vlad katz Oct 06 '20 at 14:49
  • 1
    Your `console.log()`'s [are deceiving you](https://stackoverflow.com/questions/23429203/weird-behavior-with-objects-console-log). At the point you are logging them, your arrays are empty. – Ivar Oct 06 '20 at 14:52

1 Answers1

1

This code is obsolete, also $.ajax requests are performed in parallel, so exiting early from a loop won't prevent them from being completed, unless they are explicitly aborted.

In case requests should be performed sequentially, a straightforward way to do this is async..await. $.ajax is able to 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;
};

The use of promises requires to consistently use them, either with async..await or plain then and catch. Since mycheck is able to return rejected promise on throw, an error should be handled in a caller.

If the intention of this function is to return a boolean, it can be simplified to:

    ...
    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;
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • Thank you so much Estus Flask. Will try your suggestion. – user3280899 Oct 06 '20 at 15:06
  • Estus Flask, I get the below code for console.log(userExist); Promise {} __proto__: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: false - is it possible to get the value of PromiseResult? if i can access this value from PromiseResult then my three days of my issue is resolved. – user3280899 Oct 06 '20 at 18:53
  • This was also explained in suggested question https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call . This object is a *promise* of a result. You can't get the result from it because the result isn't available at this moment. – Estus Flask Oct 06 '20 at 19:13
  • 1
    A caller should involve promises too because the whole process is asynchronous. It should either be `async` and contain `try { let result = await mycheck(thisUser) ... } catch (err) {...}`. Or use raw promises and contain `mycheck(thisUser).then(result => ...).catch(...)`. It should handle errors because they can happen. These two snippets are equivalent, but if you use transpilation and don't have a requirement to write ES5 source code then `async..await` is preferable. This is what the paragraph in the question says about. – Estus Flask Oct 06 '20 at 19:15
  • Thank you so much Estus Flask.I learned little about asunc..await today. – user3280899 Oct 06 '20 at 22:16
  • You’re welcome. Notice that async..await is just syntactic sugar for promises. Everything that’s written with it can be written with plain promises in es5/es6. It’s just makes things much more convenient in some cases, this includes asynchronous loops like the one that was shown. – Estus Flask Oct 06 '20 at 22:24