提取从promise返回的对象以推送到数组,以[[PromiseValue]]对象的形式返回Promise {<pending>}

时间:2018-02-04 00:58:52

标签: javascript arrays reactjs promise axios

我对承诺的全部想法都很陌生,也是新的反应,所以这两者的结合让我想到了这个问题。

我在反应组件中使用react.js和axios。我正在为足球设备消耗外部API。我今天所有的灯具都在循环播放,以找到两队之间的先前赛程和他们的成绩,以获得平均分数作为预测得分的方式。

在我的构造函数中,我有以下内容来设置Axios实例

constructor(props) {
    super(props);

    // the api key for consuming api
    this.apiKey = "xxxxxxxxxxxx";

    // setup axios instance
    this.instance = axios.create({
        baseURL: 'http://api.football-data.org/v1',
        headers: {
            'X-Auth-Token': this.apiKey
        }
    });

    //Holds response from API request
    this.state = {
        // all valid fixtures
        fixtures: []
    };
}

在我的componentDidMount()函数中,我调用fixtures路径来获取今天所有的灯具并循环遍历它们,找到灯具ID,然后调用另一个函数getHead2Head(),这就是我所在的位置将我的问题作为它返回的值 Promise {<pending>} [[PromiseValue]]对象包含我需要的内容。

componentDidMount() {
  let self = this;
  // call fixtures routes with timeframe of 1 day
  this.instance.get('/fixtures?timeFrame=n1').then((fixtures) => {
    // get all fixtures
    const allFixtures = fixtures.data.fixtures;
    // create valid fixtures array to add all fixture details to pass to fixtures state
    let validFixtures = [];
    // loop through all fixture objects in allFixtures array
    for (var i = 0; i < (allFixtures.length); i++) {
      // check if valid fixture, returns true or false
      let isValid = self.isValid(allFixtures[i]);
      // if fixture is valid
      if (isValid) {
        // get id of fixture to pass through to fixture route with id query
        let fixtureId = allFixtures[i]._links.self.href.split('v1/').pop();
        // home teams name
        let homeTeam = allFixtures[i].homeTeamName;
        // away teams name
        let awayTeam = allFixtures[i].awayTeamName;
        // call head2head function to get all previous results from the two teams playing
        let h2hAvgScores = self.getHead2Head(fixtureId, homeTeam, awayTeam);
        // this returns Promise {<pending>} with [[PromiseValue]] object containing what I need, how to get access to this to assign to valid fixtures array???
        console.log(h2hAvgScores);
        // push object with named values to fixtures array, not working as can't get correct value from h2hAvgScores???
        validFixtures.push({
          'homeTeam': homeTeam,
          'awayTeam': awayTeam,
          'homeTeamAvgScore': h2hAvgScores.homeTeamAvgScore,
          'awayTeamAvgScore': h2hAvgScores.awayTeamAvgScore
        });
      }
    }
    this.setState({
      fixtures: validFixtures
    });
  }).catch((error) => {
    console.log(error);
  });
}

下面是我的getHead2Head()功能,我已经将灯具ID,主队名称和客队名称作为参数传递。夹具ID是api调用中用于获得夹具头部结果的路径。我遍历每个头到头会议获得结果,将它们传递给一个数组,然后得到数组中每个整数的平均值,并返回归属和离开团队的平均值返回到componentDidMount()函数

getHead2Head(id, home, away) {
  let self = this;
  // creature empty arrays to later push scores from previous fixtures to.
  let homeTeamScores = [];
  let awayTeamScores = [];
  // set getAvgScores variable that get's instance of the head2head results of passed fixture
  let getAvgScores = this.instance.get(id + '?head2head=20').then((f) => {
    // get head2head value
    const h2h = f.data.head2head;
    // get head2head fixtures
    const fixtures = h2h.fixtures;
    // loop through all head2head fixtures
    for (var i = 0; i < fixtures.length; i++) {
      // returns true or false if hometeam of fixture is equal to hometeam of head2head fixture
      let sameFixture = this.sameFixture(fixtures[i], home);
      if (sameFixture) {
        // get the home and away team scores
        // returns as eg. { 'homeTeamScore': 2, 'awayTeamScore': 1 }
        let score = self.getFixtureScore(fixtures[i], home, away);
        // get home and away team scores from score object;
        let homeTeamScore = score.homeTeamScore;
        let awayTeamScore = score.awayTeamScore;
        // push home score to homeTeamScores array
        homeTeamScores.push(homeTeamScore);
        // push away score to awayTeamScores
        awayTeamScores.push(awayTeamScore);
      }
    }
    // return null if no previous head to head fixtures
    let homeTeamAvgScores = homeTeamScores.length > 0 ? homeTeamScores : null;
    let awayTeamAvgScores = awayTeamScores.length > 0 ? awayTeamScores : null;
    // gets average of all intergers in array and Math.round
    // returns as integer
    let hAvgScore = homeTeamAvgScores !== null ? self.getAvgScore(homeTeamAvgScores) : null;
    let aAvgScore = awayTeamAvgScores !== null ? self.getAvgScore(awayTeamAvgScores) : null;
    // return object to set value to getAvgScores variable
    return ({
      'homeTeamAvgScore': hAvgScore,
      'awayTeamAvgScore': aAvgScore
    });
  }).catch((error) => {
    console.log(error);
  });
  // return getAvgScores to componentDidMount
  return getAvgScores;
}

我遇到的问题是getAvgScores变量等于Promise {<pending>}并返回h2hAvgScores Promise {<pending>}。这确实包含一个名为[[PromiseValues]]的值,其中包含我需要的对象。

如何从h2hAvgScores变量中提取此对象以将h2hAvgScores.homeTeamAvgScore传递到validFixtures数组?

任何帮助都会非常感激,如果难以理解,请道歉,我的js行话并没有达到应有的速度。

编辑:

在建议的回答之后我尝试了then()功能,但我不确定我应该返回什么作为返回任何内容并引用&#39; h2hAvgScores&#39;仍然给我Promise {<pending>}

的相同结果
let h2hAvgScores = self.getHead2Head(fixtureId, homeTeam,awayTeam).then((avg) => {
  return avg.homeTeamAvgScore;
});

然后尝试推送到validFixtures数组,当尝试使用validFixtures数组设置状态时,此时它就是空的,所以我还是有点无能为力? ?

let h2hAvgScores = self.getHead2Head(fixtureId, homeTeam, awayTeam).then((avg) => { 
  return validFixtures.push({ 'homeTeam': homeTeam, 'awayTeam': awayTeam, 'homeTeamAvgScore': avg.homeTeamAvgScore, 'awayTeamAvgScore': avg.awayTeamAvgScore });
});

0 个答案:

没有答案