简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM