ES6类方法返回undefined

时间:2017-02-17 10:26:57

标签: javascript node.js class ecmascript-6

我正在使用Node,Babel,Express,我有这段代码

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;

但是,初始化类whit

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

getSummonerId方法返回undefined,任何想法?

1 个答案:

答案 0 :(得分:3)

您的getSummonerId函数是异步的。要获得返回值,您必须使用callback函数或返回Promise。您几乎已经回复了承诺,但忘记了return关键字。

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

然后你可以使用

获取值
let lolapi = new lolApi(summoner, region);
lolapi.getSummonerId().then(lolData => console.log(lolData));