簡體   English   中英

如何在map函數中調用api

[英]How to call api within map function

嗨,我正在嘗試在地圖中進行 api 調用,但它只是作為 object.promise 返回。 是否可以在其中調用 api 而不將其作為 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> 
   )
  }```

您正在使用map創建一系列承諾。 使用Promise.all來解析Promise.all數組。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM