Search code examples
javascriptfor-loopwait

Promise should return data after end two for loop


which get data from API:

const countries = [
  'Spain',
  'England',
];

const getLeagueID = () => {
  const newData = [];

  return new Promise(resolve => {
    for (let i = 0; i < countries.length; i++) {
      getApi(`https://www.thesportsdb.com/api/v1/json/1/search_all_leagues.php?c=${countries[i]}`)
        .then(({ countrys }) => {
          countrys.forEach((league, index) => {
            if (league.strSport === 'Soccer') {
              const getData = {
                strSport: league.strSport,
                strLeague: league.strLeague,
              };
              newData.push(getData);
            }
            if (index === countrys.length - 1 && i === countries.length - 1) {
              resolve(newData);
            }
          });
        })
        .catch(err => {
          console.log(err);
        });
    }
  });
};

In first for loop I doing increment by countries from list. When Api return data I create second foreach method. Inside this method I get data and push it to arra newData. The problem is with resolve:

if (index === countrys.length - 1 && i === countries.length - 1) {
    resolve(newData);
}

I don't know how to write instruction if, which wait for the end foreach and for loop. My instruction if is wrong because not return all data. First time return 3 records, next time 7 records.


Solution

  • It's work, but sure that it can be improved

    const getLeagueID = () => {
        return new Promise((resolve, reject) => {
            const promises = [];
            for (let i = 0; i < countries.length; i++) {
                promises.push(
                    getApi(`https://www.thesportsdb.com/api/v1/json/1/search_all_leagues.php?c=${countries[i]}`)
                );
            }
        
            Promise.all(promises)
            .then(res => {
                const newData = [];
                res.map(row => {
                    const data = JSON.parse(row);
                    const {countrys} = data;
                    countrys.forEach((league, index) => {
                        if (league.strSport === 'Soccer') {
                        const getData = {
                            strSport: league.strSport,
                            strLeague: league.strLeague,
                        };
                        newData.push(getData);
                        }
                    });
                });
                resolve(newData);
            })
            .catch(err => {
                console.log(err);
                reject(err);
            });
        });
      }