Quit a function from a $ .each

11

I'm using the $ .each function of jQuery to run a JSON , and given some validation I want to show a alert() , leave the $.each and the function that contains it, I know that return false; leaves the function $.each , but continues with the execution of the function.

Example

function guardarCuestionario() {
    var preguntas = JSON.parse('cadena de texto con formato JSON');

     $.each(preguntas, function () {
          value = $("input:radio[name ='" + this.ID + "']:checked").val();

          if (this.EsObligatoria && value === undefined) { 
              alert('Necesitas seleccionar una respuesta para todas las preguntas que no son opcionales');
              return false; // solamente se sale del $.each pero no de la funcion
          }
          /*
              Mas código 
          */
     });
     console.log('No quiero que continúe hasta aquí si (this.EsObligatoria && value === undefined) se cumple!!!');
     /*
         Mas código 
     */
}

I know that I can achieve what I want by assigning a value to a flag to know if at some point I enter the condition and check it at the end, but I want to know if there is any way out of the $.each and the function that the contains in a sentence.

    
asked by Enrique Zavaleta 08.12.2015 в 16:40
source

3 answers

7

One possible solution is to use exceptions. The code would be simple:

  • Wrap the call to the function within a try with a catch empty.
  • When you reach the stop condition, throw an exception with throw .

For example, in this demonstration an array of 6 elements is iterated, the stop condition is that only two of them are shown, and after that it jumps to the end without displaying the message "I do not want to continue up to this point!" (look at the JavaScript console to see the results):

function guardarCuestionario() {
    var preguntas = JSON.parse('[1,2,3,4,5,6]');
    $.each(preguntas, function(i, e) {
        if (i == 2) {
            throw "Cualquier Cosa";
        }
        console.log(e);
    });
    console.log('No quiero que continúe hasta aquí!');
}

try {
    guardarCuestionario();
} catch (e) { }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

And applied to your particular code would look like this:

function guardarCuestionario() {
    var preguntas = JSON.parse('cadena de texto con formato JSON');

    $.each(preguntas, function () {
        value = $("input:radio[name ='" + this.ID + "']:checked").val();

        if (this.EsObligatoria && value === undefined) { 
            alert('Necesitas seleccionar una respuesta para todas las preguntas que no son opcionales');
            throw "error"; // salta al catch
        }
        /*
        Mas código 
        */
    });
    console.log('No quiero que continúe hasta aquí si (this.EsObligatoria && value === undefined) se cumple!!!');
    /*
    Mas código 
    */ 
}

try {
    guardarCuestionario();
} catch(e) { }
    
answered by 08.12.2015 / 17:21
source
6

There is no native way to achieve it. The function each does not belong to the JavaScript syntax, therefore, its use is the same as that of any other function.

There are several techniques to achieve what you want. One of them is the use of an exception StopIterationException or similar, that you can throw when you decide to stop the iteration. Personally I do not like it.

Another option is to use Array.prototype.some instead of each of jQuery. As soon as you find the stop condition (where you would put a break ) you should use a return true , which indicates the stop condition for some . The return value of some should be checked to see if you will escape the function.

function saveQuestionnaire () {     var questions = JSON.parse ('text string with JSON format');

 var escapa = preguntas.some(function () {
      value = $("input:radio[name ='" + this.ID + "']:checked").val();

      if (this.EsObligatoria && value === undefined) { 
          alert('Necesitas seleccionar una respuesta para todas las preguntas que no son opcionales');
          return true; // regresa true para indicar que debe escapar de la función
      }
      /*
          Mas código 
      */
 });
 if (escapa) {
     return;
 }
 console.log('No quiero que continúe hasta aquí si (this.EsObligatoria && value === undefined) se cumple!!!');
 /*
     Mas código 
 */

}

Obviously, an auxiliary variable is still used in both cases (return value of some or exception cachada). If what you want is to have a simpler code, you will probably want to use a classic for .

    
answered by 08.12.2015 в 17:20
4

I do not understand what the problem is? If you leave the $ .each with the return, it's just that you use a variable as an output parameter ... example:

function guardarCuestionario() {
   //... code code code
   var exit = false;
   $.each(preguntas, function () {

       if (this.EsObligatoria && value === undefined) { 
          exit = true;
          return false;
       }
       //... code code code
   });

   exit && return; //si no te gusta así, estas libre de utilizar un if jeje
   //... code code code
}

The exceptions are good but they are not the answer for everything, and less for this case;)

    
answered by 08.12.2015 в 21:02