Problem with Return

Asked

Viewed 38 times

1

I have a problem with return since the node is all asynchronous.

var myFUNC = function(A, B) {
    A.every(function(AA) {        
        return (AA === B);
    });

    return true;
};

if(!myFUNC(...)) {
    ....
}

obviously the function always returns true but she shouldn’t be doing this, as I’m starting with node, I don’t know how to resolve this impasse.

She should follow the following logic:

  • sweeps the array A
  • if AA === B for false he stops walking the array and returns false
  • if no item from array return false then return true

1 answer

7


The problem with your code is not that it is running asynchronously. The problem is that you are ignoring the result of the call A.every(...) (which is executed synchronously) - if all return (AA === B) are true, then every returns true (or false if any of them aren’t true).

You can rewrite your function as follows:

var myFUNC = function(A, B) {
    var todosIguais = A.every(function(AA) {        
        return (AA === B);
    });

    return todosIguais;
};

if(!myFUNC(...)) {
    ....
}
  • I hadn’t noticed that, +1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.