Promise应在第二个for循环后返回数据

问题描述

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

在第一个for循环中,我按列表中的国家/地区进行递增。 当Api返回数据时,我创建了第二个foreach方法。在此方法内,我获取数据并将其推送到arra newData。问题出在resolve上:

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

我不知道如何编写指令,如果指令等待foreach和for循环结束。我的指令是否错误,因为未返回所有数据。第一次返回3条记录,下次返回7条记录。

解决方法

这是可行的,但请确保可以对其进行改进

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