Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!