简体   繁体   中英

How to call api within map function

Hi im trying to do an api call within a map, however it just returns as an object.promise. Is there away to call api within it without it returning as an object.promise

const MatchHistory = ({ history }) => {
    const Match=[];


      return (
        <div>
          <p>
           {history.map( hist => (
            axios.get('https://polar-hollows-37538.herokuapp.com/matchdata/'+hist.gameId).then(response => (Match.push(response.data.platformId))),
            console.log('get:'+axios.get('https://polar-hollows-37538.herokuapp.com/matchdata/'+hist.gameId).then(response =>(Match.push(response.data.mapId)))),
            <Card>
              <img src={'img\\'+hist.lane+'.png'}></img>
              <li key={hist.gameId}>
              <h5 className="card-title1">Lane:{hist.lane}</h5> 
              <h5 className="card-title1">Role:{hist.role}</h5> 
              <h5 className="card-title1">Champion:{hist.champion}</h5> 
              <h5 className="card-title1">GameId:{hist.gameId}</h5>
              </li>
            </Card>
      ))}}
        </p> 
      </div> 
   )
  }```

You are creating array of promises using map . Use Promise.all to resolve the array of promises.

const promises = history.map(hist => axios.get('https://polar-hollows-37538.herokuapp.com/matchdata/'+hist.gameId));

const Match = [];

Promise.all(promises)
.then(function(values) {
  values.forEach(value => {
      Match.push(value.data.platformId);
  })
})
.catch(err => {
    console.error(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