如何使用riot-lol-api连续发出多个请求?

时间:2018-11-05 10:32:35

标签: javascript node.js promise

情况:

我有一个现有的代码库,该代码库使用另一个库向Riot API发出请求。可悲的是,说图书馆有一些问题,所以我决定改用这个图书馆:

https://www.npmjs.com/package/riot-lol-api

https://github.com/Neamar/riot-lol-api/blob/master/lib/index.js

唯一的问题:该库似乎没有使用Promises,而旧库却使用了Promises,因此我很难适应新的库。


代码:

var urls = [];

    for (var i = 0; i < enemies.length; i++) {
         urls.push('/lol/league/v3/positions/by-summoner/'+enemies[i].summonerId);
    }

    let promises = urls.map(url => fetchData(url, region, "league"));

    Promise.all(promises).then(responses => {

         console.log("RESPONSES: "+responses);

...

function fetchData(url, region, tag) {

// This used to be a promise when the old library was used

riotRequest.request(region.toLowerCase(), tag, url, function(err, data) {
    if (!err) {
        return data;
    } else {
        console.error("ERROR FIRST ITERATIONS: "+err);
        res.render("threat", {errorMessage: "Player not found ! The game must either have started or be on the loading screen.", finalPlayers: undefined});
    }
});

}

现在,这当然不起作用,但可以将其视为伪代码来解释我在这里想要实现的目标。


输出:

RESPONSES: ,,,,

问题:

如何使我的代码适应新的库?

1 个答案:

答案 0 :(得分:1)

当我写图书馆的时候,诺言真的很慢。使用promise可以使我每个CPU每秒发送700个请求,而无需保证我每个CPU每秒可以处理1000个请求。

如果在您的情况下性能不是问题,则可以使用此小包装将回调样式函数转换为Promise:

let RiotRequest = require('riot-lol-api');

let riotRequest = new RiotRequest('<your-key>');

// This function will return a promise that you can then use with Promise.all
function promisifiedRequest(region, group, endpoint) {
  return new Promise((resolve, reject) => {
    riotRequest.request(region, group, endpoint, function(err, res) {
      if(err) {
        reject(err)
      }
      else {
        resolve(res);
      }
    })
  });
}

// Example use:
promisifiedRequest('euw1', 'summoner', '/lol/summoner/v3/summoners/by-name/graphistos').then(function(response) {
  console.log("Result:", response);
}).catch(console.log)