Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda