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

112
Visualizações
Function returning before data is processes

I thought for loops were blocking in Javascript, but this function is returning an empty array before the for loop finishes. Is the answer to this to setup a new function with just the for loop as a promise? If so what does that look like, the syntax for a promise is really confusing to me.

async function retrieve_s3_file(to_do_list, guid){
  var data_list = [];

  for (let i = 0; i < to_do_list.length; i++)
  {
    element = to_do_list[i];
    console.log("\n\nOutgoing request /jobs/list?guid=" + guid + "&file=" + element);
    axios.get(job_queue_url + "?guid=" + guid + "&file=" + element)
    .then(function (res){
      data_list.push(res.data);
      console.log("Inside Loop: " + JSON.stringify(data_list));
    })
    .catch(function (error){
      console.log(error);
    });
  }

  console.log("Data List: " + JSON.stringify(data_list));
  return JSON.stringify(data_list);
}
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Javascript is single threaded and thereby loops are usually blocking, but in this case your promises will put it's new tasks at the end of the stack. If you use await no new task should be created and it should behave as you want. But you are making it sycronus so it will be a little slower than before.

async function retrieve_s3_file(to_do_list, guid){
  var data_list = [];

  for (let i = 0; i < to_do_list.length; i++)
  {
    element = to_do_list[i];
    console.log("\n\nOutgoing request /jobs/list?guid=" + guid + "&file=" + element);
    await axios.get(job_queue_url + "?guid=" + guid + "&file=" + element)
    .then(function (res){
      data_list.push(res.data);
      console.log("Inside Loop: " + JSON.stringify(data_list));
    })
    .catch(function (error){
      console.log(error);
    });
  }

  console.log("Data List: " + JSON.stringify(data_list));
  return JSON.stringify(data_list);
}
about 4 years ago · Santiago Trujillo Relatório

0

axios.get is a promise. In javascript a promise is non blocking, meaning the callback given in the then function will run once the promise resolve. But the promise won't block the thread.

The below example reflects the problem of the question. The console prints start end then ok. Because customPromise is a promise and it is called without the await, the caller won't wait for that promise to finish, so the caller will continue the execution and print end. Note that this promise is resolved immediately but the callback res => console.log(res) will be executed at the end because its a promise callback.

const customPromise = new Promise((resolve, reject)=>{resolve('ok')})


function nonBLockingExample (){
  console.log('start');
  customPromise.then(res => console.log(res));
  console.log('end');
}

nonBLockingExample();

Below is an example of the desired output. The caller waits for the customPromise to resolve because customPromise is called with the await keyword.

const nonBlockingPromise = new Promise((resolve, reject)=>{resolve('ok')})

async function bLockingExample (){
  console.log('start');
  await nonBlockingPromise.then(res => console.log(res));
  console.log('end');
}

bLockingExample();

So to apply the fix to your code, just await axios.get. (await axios.get(.....)

about 4 years ago · Santiago Trujillo Relatório

0

If you use asynchronous operation it won't block.

You can use await keyword if you want Axios to wait before the request ends otherwise use promises. Collect them and using Promise.all you can get all the responses as an array when all requests are resolved.

async function retrieve_s3_file(to_do_list, guid) {
  const requests = [];
  for (const file of to_do_list) {
    const params = new URLSearchParams({ guid, file });
    const request = axios.get(`${job_queue_url}?${params.toString()}`);
    requests.push(request.then((response) => response.data));
  }

  return Promise.all(requests).then(JSON.stringify);
}
about 4 years ago · Santiago Trujillo 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