【问题标题】:Riot API Promise All With FetchRiot API Promise 全部使用 Fetch
【发布时间】:2020-10-05 07:06:22
【问题描述】:

我正在尝试循环播放 10 场英雄联盟比赛,并且对于每场比赛,调用另一个 api 来获取比赛详情。到目前为止,我有一个这样的功能设置:

function getAllMatchData(ids) {
    const promises = [];
    _.take(ids, 1).forEach(id => {
        const promise = fetch(`https://na1.api.riotgames.com/lol/match/v4/matches/${id}`, {
            headers: {"X-Riot-Token": token}})
        promises.push(promise);
    })
    return Promise.all(promises);
}

由于 api 返回 100 个匹配项,我只取前 10 个,然后用它们创建一个 promise 数组。然后我这样做以获得结果:

getAllMatchData(_.map(data['matches'], 'gameId')).then(results => {
     console.log(results);
}).catch(error => {
     console.log(error);
})

但结果的控制台日志中没有任何 json 数据。它打印出如下所示的对象数组:

Response {
    size: 0,
    timeout: 0,
    [Symbol(Body internals)]: { body: [Gunzip], disturbed: false, error: null },
    [Symbol(Response internals)]: {
      url: 'https://na1.api.riotgames.com/lol/match/v4/matches/3556728982',
      status: 200,
      statusText: 'OK',
      headers: [Headers],
      counter: 0
    }
  }

我不确定 JSON 数据响应在哪里。

【问题讨论】:

    标签: javascript node.js express promise


    【解决方案1】:

    使用 fetch,您需要使用您收到的响应类型来解析响应。

            const promise = fetch(`https://na1.api.riotgames.com/lol/match/v4/matches/${id}`, {
                headers: {"X-Riot-Token": token}}).then(res => res.json())
    
    

    在您的情况下,它是 json。所以就像调用res.json()一样简单。

    【讨论】:

      猜你喜欢
      • 2020-11-09
      • 2019-12-19
      • 2017-10-22
      • 1970-01-01
      • 2016-10-16
      • 2021-09-20
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      相关资源
      最近更新 更多