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

94
Visualizações
JS fetch response as variable

I need some guidance please.

Pure JS only, no jQuery please.

I'm assigning a fetch response to a variable at the top of the *.js file (multiple different fetch + vars, both GET and POST):

  var srcDL;
  fetch(url)
  .then(response => response.json())
  .then(data => srcDL = data);

This works ok, however later in the same file, I'm trying to iterate through the object, but the error is telling me srcDL is undefined.

Uncaught TypeError: Cannot read properties of undefined (reading 'length')...

I assume this is because the fetch is async, so the rest of the file is being executed before the fetch gets a successful response and has updated the variable.

  Array.from(document.querySelectorAll('.AU_dList')).forEach(function(e){
    var idx = e.getAttribute('data-idx');
    var selitem = e.getAttribute('data-selitem');
    var s = '';
    var data = '';
    for( var i = 0; i < srcDL.length; i++ ){
      s = srcDL[i]['pk']==selitem ? ' selected' : ''; 
      data = data + '<option value="' + srcDL[i]['pk'] + '" '+ s +'>' + srcDL[i]['name'] + '</option>';
    }
    document.getElementById("dept_"+idx).innerHTML = data;
  });

I tried to wrapping the Array.from.... together with many other functions which depend of the fetch response to variable, into a delay with setTimeout(). This partially works, until another event needs to reference a function created inside of / after the setTimeout() has completed, resulting in another error:

<function> is not defined at HTMLSelectElement.onchange

Reading about async/await, this doesn't really solve my needs, because (if I understand it correctly), every instance of my DOM with class .AU_dList, will call the fetch url. Therefore calling the database several times in the same file getting the same response. Hence I want to initially make the call to DB, save the response under a variable, then use in within the file as many times as needed.

What is the best approach to have this working as expected? The fetch being ultra quick, or not being asynchronous? Am I nearly there or completely missed the point?

EDIT: Please re-open, this is not a duplicate.

about 4 years ago · Juan Pablo Isaza
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