0

!I'm a beginner in js! is there any way to let the return wait for both for loops to finish I tried all the solutions here " https://stackoverflow.com/questions/27914209/how-could-i-run-a-function-after-the-completion-of-a-for-loop-in-node-js" but no one of them works I think because is nested loop


function StatisticsPerGameId (IDs){
    console.log(IDs)
    let doubldoubl={};
    for (let i=0; i <IDs.length;i++){
        const options = {
            method: 'GET',
            url: 'https://api-nba-v1.p.rapidapi.com/players/statistics',
            params: {game: IDs[i]},
            headers: {
              'X-RapidAPI-Host': 'api-nba-v1.p.rapidapi.com',
              'X-RapidAPI-Key': 'afgsdgbsdghbrynhndf6hn6dfhndfhn61dhddfhn'
            }
          };
          
          axios.request(options).then(function (response) {
            console.log(response.data.response[0].points)
            for(let j in response.data.response){
                let dd = 0;
                if( response.data.response[j].points >= 10){dd=dd+1;};
                if( response.data.response[j].totReb >= 10){dd=dd+1;};
                if(dd == 2 ){
                    doubldoubl=doubldoubl+{
                        name:response.data.response[j].player.firstname +" "+ response.data.response[j].player.lastname,
                        teamOfplayer : response.data.response[j].team.name,
                        teamOfplayerlogo:response.data.response[j].team.logo,
                    }
                };
                dd = 0 ;
            }
          }).catch(function (error) {
              console.error(error);
          }); 
    }
    return doubldoubl;
}

1 Answers1

0

axios.request() returns a promise, which will resolve asynchronously when the request is fetched. Calling .then(function () {...}) will call that function when the request is ready.

The best way to wait for all the requests is to pass them all into Promise.all():

function StatisticsPerGameId (IDs){
    ...
    const promises = []
    for (let i=0; i <IDs.length;i++){
        ...
          const promise = axios.request(...).then(function (response) {...}).catch(function (error) {...}); 
          promises.push(promise)
    }
    return Promise.all(promises).then(function () {
        return doubldoubl;
    });
}

Note that this will make StatisticsPerGameId return a promise for the result, which will similarly need to be waited on asynchronously.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#composition

Rahat Ahmed
  • 2,191
  • 2
  • 30
  • 40