Home > Mobile >  NodeJs wait until all calls in loop are finished
NodeJs wait until all calls in loop are finished

Time:02-23

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');
    })
}

CodePudding user response:

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.

CodePudding user response:

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
}

CodePudding user response:

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)
        })
    })
}
  • Related