0

I'm using Node, Babel, Express and I have this code

import express from 'express';
import httpinvoke from 'httpinvoke';

export class lolApi{

  constructor(summoner, region) {
    this.summoner = summoner;
    this.region = region;
    this.methods = {
      "currentGame": `/observer-mode/rest/consumer/getSpectatorGameInfo/${this.region}/`,
      "matchList": `/api/lol/${this.region}/v2.2/matchlist/by-summoner/`,
      "summonerName": `/api/lol/${this.region}/v1.4/summoner/by-name/`
    };

    this.domain = `https://${this.region}.api.pvp.net`;

    this.apiKey = "xxxxxxxxxx";
  }

  getSummonerId() {
    let url = `${this.domain}${this.methods.summonerName}${this.summoner}?api_key=${this.apiKey}`;
    httpinvoke(url, 'GET').then((res) => {
       this.data = JSON.parse(res.body);
      return this.data;
    }, (err) => {
      console.log(err);
    });
  }
}


export default lolApi;

But, when initialize the class whit

let lolapi = new lolApi(summoner, region);
let lolData = lolapi.getSummonerId();
console.log(lolData);

The getSummonerId method returns undefined, any idea?

  • getSummonerId function in not returning anything. – Sanchay Kumar Feb 17 '17 at 10:29
  • Please have a look at how promises work: http://stackoverflow.com/questions/22536385/setting-a-variable-to-get-return-from-call-back-function-using-promise – nils Feb 17 '17 at 10:30
  • That is because it does not return anything. it just makes an async call. –  Feb 17 '17 at 10:30
  • `lolapi.getSummonerId().then(function(result){ console.log(result); });`, as mentioned above, read about [javascript promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) – piotrbienias Feb 17 '17 at 10:31

1 Answers1

4

Your getSummonerId function is asynchronous. To get the return value you must use either a callback function or return a Promise. You already almost are returning a promise, but you forgot the return keyword.

 getSummonerId() {
    let url = `${this.domain}${this.methods.summonerName}${this.summoner}?api_key=${this.apiKey}`;
    return httpinvoke(url, 'GET').then((res) => {
       this.data = JSON.parse(res.body);
      return this.data;
    }, (err) => {
      console.log(err);
    });
  }

and then you can get the value using

let lolapi = new lolApi(summoner, region);
lolapi.getSummonerId().then(lolData => console.log(lolData));
ThomasThiebaud
  • 11,331
  • 6
  • 54
  • 77