Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

180
Vistas
JavaScript function jumps to return neglecting any logic in between

Now I am using JavaScript function coded as follows:

self.fillSelect = function (key) { 
             html = "<option value =''>choose</option>";
            self.getGroupOptions(key, function (res) {
                for (let a = 0; a < res.length; a++) {
                    html += "<option value = '" + res[a].Code_Name + "'>" + res[a].Code_Name + "</option>";
                   
                }
            }, function (err) {
            });
            return html;
        }

As I know or understand the html variable is a global variable and can be accessed in any place in the function. In this function this logic happens after the return statement. This function just returns

<option value =''>choose</option>

then enters the loop with no result...why is that happening??

self.getGroupOptions()

This function is a jQuery AJAX request to get options from database

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

TLDR

You should learn about javascript asynchronous functions and callbacks. The for loop that populates the html is inside a function that gets called later, in async.

Long version

JavaScript is single threaded, that means that there is a single line of execution and things cannot happen "at the same time" in two places of a JS software, be it a page or a node JS application.

To work around this "feature", in JS is very common to run async operations providing a callback.

The underlying system (in this case, the browser) will perform the operation (in this case, an AJAX call) and then "call back" your code by invoking a provided function.

This is what is happening in this case, the call to AJAX happens later, your code return before.

Then when the AJAX call happens, you call is called as part of the "call back", the for loop executes, the html variable is filled, but at that moment is too late to return it.

You should return a Promise and register a callback on that promise to be able to retrieve the html content later, when all the AJAX stuff and callback is completed.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda