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

309
Visualizações
NodeJs wait until all calls in loop are finished

I have the following code in node (beginner), I want to call a function after all the code has been executed in the loop, I know that I have to use promises, but I don't know how to apply them in this situation. The code has been simplified. Many thanks.

const axios = require('axios').default;

axios.post('url', {
    params: {}
}).then(response=>{
    var objResponse = response.data
    Object.keys(objResponse).forEach(function (key){
        axios.post('url', {
            params: {}
        }).then(response=>{
            var n=0;
            getCode(n);
        })
    })
    **finishFunction**()
})

function getCode(n) {
    axios.post('url', {
        params: {}
    }).then(response=>{
        if(response.data){
            if (response.data.code) {
                getData();
            }else{
                if (n < 10) {
                    n++;
                    getCode(n);
                } else {
                    getTimeout();
                }
            }
        }
    })
}

function getTimeout() {
    axios.post('url', {
        params: {}
    })
}

function getData() {
    axios.post('url', {
        params: {}
    }).then(response=>{
        console.log('finished one loop');
    })
}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Best way to achieve what you want is to use async/await with a regular for-loop.

Here is an example of what I mean. You can adjust it to your needs:

async doSomeStuff() {
    const results = []

    const res1 = await axios.post('url', {
        params: {}
    })
    
    // assuming res1 is an Array
    for (let i=0; i < res1.length; i++) {
        const result = await axios.post('url2', {
            params: {}
        })
        results.push(result)
        
    }

    return results
}

You can also call other async functions inside the loop as you are doing.

over 4 years ago · Santiago Trujillo Relatório

0

You could use Promise all and map together, alongside async/await

async function myFunction(){
  const result = await axios.post('url');
  const keys = Object.keys(result.data);
  const requests = keys.map((key, i) => axios.post('url')/*chain more if u need*/)
  const allResults = await Promise.all(requests);
  // All done run your function below
}
over 4 years ago · Santiago Trujillo Relatório

0

If you are happy for each item in the loop to be run at the same time, you can use an array of promises and wait for everything in the array to finish. Then you just have to add promises to your functions which will take an unknown amount of time to run. Something like this might get you started:

   const axios = require('axios').default;

axios.post('url', {
    params: {}
}).then(response=>{
    var objResponse = response.data
    var proms = [];
    Object.keys(objResponse).forEach(function (key){
        proms.push(
            axios.post('url', {
                params: {}
            }).then(response=>{
                var n=0;
                return getCode(n);
            })
        )
    })
    var items = Promise.all(proms);
    items.then(function (results) {
       // **finishFunction**()
    });
    
})

function getCode(n) {
    return new Promise(function (resolve, reject) {
        axios.post('url', {
            params: {}
        }).then(response=>{
            if(response.data){
                if (response.data.code) {
                    getData();
                }else{
                    if (n < 10) {
                        n++;
                        getCode(n).then(data => {
                            return resolve(data)
                        });
                    } else {
                        getTimeout().then(data => {
                            return resolve(data)
                        });
                    }
                }
            }
        })
    })
}

function getTimeout() {
    return new Promise(function (resolve, reject) {
        axios.post('url', {
            params: {}
        })
        return resolve()
    })
}

function getData() {
    return new Promise(function (resolve, reject) {
        axios.post('url', {
            params: {}
        }).then(response=>{
            console.log('finished one loop');
            return resolve(response)
        })
    })
}
over 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