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

135
Visualizações
How do i make javascript loop wait for each iteration of loop to finish before starting the next?

I have a loop that gets iterated through 1000 times where each iteration makes a request and then prints the result of that request.

Similar to below.

let start = console.log(Date.now())
for (i = 0; i < 1000; i++) {
    request.then(data => {
        console.log(Date.now() - start)
    })
}

This however results in the first request taking much longer to be completed then if there was just 1 iteration of the loop.

with i < 1000:

5860
...

with i < 1:

220,
...

For the aim of this script however, I want to wait for each result to be received before starting the next iteration of the loop.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If you want to stick with the ES5 way of handling Promises, you could use the following approach:

const start = console.log(Date.now())

// Create a instantly resolved promise
for (let i = 0, p = Promise.resolve(); i < 1000; i++) {
  // append new promise to the chain
  p = p.then(() => request()
       .then(() => console.log(Date.now() - start));
}

If you can use ES6 methods, you could write this using the async/await pattern like so:

const asyncLoop = async () => {
  const start = console.log(Date.now())

  for (let i = 0; i < 1000; i++) {
    const data = await request();
    console.log(Date.now() - start);
  }
}

asyncLoop();

The chance that you really want to make the requests one after the other is actually pretty small though, so in case you want to make the request simultaneously, but do something after all of them resolved, you can use Promise.all(...)

const start = console.log(Date.now())
const requests = [request1, request2, ...];

Promise.all(requests)
       .then(() => console.log(Date.now() - start));
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use the async-await pattern here. You can achieve this by changing the code

async function iteration() {
    let start = console.log(Date.now())
    for (let i = 0; i < 1000; i++) {
        const data = await httpRequest()
        console.log(Date.now() - start)
    }

}

async function httpRequest() {
    return new Promise((resolve, reject) => {
        request.then(data => {
            //Do anything you want to do with data
            resolve(data)
        }).catch(error => {
            console.error(`Error in request`)
            reject(error)
        })
    })
}

Explanation:

  1. I have moved the request code in a separate function httpRequest and this function will return promise on success
  2. I called httpRequest in for loop using await keyword, now loop will wait till the request is completed
  3. I have also wrapped for loop code in function since you can only use await inside an async function
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