Как преобразовать объект обещания в объект в классе - PullRequest
0 голосов
/ 05 июня 2019

Я хочу получить данные извне моего проекта с помощью axios.я делаю это в стороне от класса, но по какой-то причине я получаю данные в объекте обещания, я использую await и обещание, но в конечном итоге я получаю данные в [обещании объекта].

const Online_Visitors_System = class OnlineVisitors {
  constructor() {
    // get VisitorIP
    this.IP = this.fetchIP();
    // config redis for key space notification
    this.redis = Redis.createClient();
    this.redis.on("ready", () => {
      this.redis.config("SET", "notify-keyspace-events", "KEA");
    });
    PubSub.subscribe("__keyevent@0__:incrby");
  }
  async fetchIP() {
    return new Promise((resolve, reject) => {
      return axios
        .get("https://api.ipgeolocation.io/getip")
        .then(res => resolve(res.data.ip));
    });
  }
  VisitorInter() {
    console.log(this.IP);
  }
};

module.exports = new Online_Visitors_System();

ошибка, с которой я сталкиваюсь:

This is converted to "[object Promise]" by using .toString() now and will return an error from v.3.0 
on.
Please handle this in your code to make sure everything works as you intended it to.
Promise { '51.38.89.159' }

Ответы [ 2 ]

0 голосов
/ 05 июня 2019

Ну, вы пропустили ожидание в нескольких местах, вот полная коррекция:

const Online_Visitors_System = class OnlineVisitors{
    constructor(){
        // get VisitorIP
        this.fetchIP().then(ip => this.IP = ip);

        // config redis for key space notification
        this.redis = Redis.createClient();
        this.redis.on('ready',()=>{
            this.redis.config('SET',"notify-keyspace-events",'KEA')
        })
        PubSub.subscribe("__keyevent@0__:incrby")
    }
    fetchIP(){
        return new Promise((resolve,reject)=>{
            axios.get('https://api.ipgeolocation.io/getip')
            .then(res=>resolve(res.data.ip))     
        })
    }
 VisitorInter(){
     console.log(this.IP)
 }
};

Поскольку метод fetchIP является асинхронной функцией, вам также нужно await при ее вызове, поэтому: this.IP = await this.fetchIP(),Но так как вы находитесь в конструкции, вы не можете использовать await, поэтому решение состоит в том, чтобы использовать chaning: this.fetchIP().then(ip => this.IP = ip);

Обратите внимание, что при запуске нового Promise вам нужно дать ему функцию async, потому что внутричто вы ожидаете других методов.

0 голосов
/ 05 июня 2019

Вы присваиваете обещание IP-адреса на this.IP.

Вам потребуется .then обещание, чтобы получить фактический IP-адрес;он может быть или не быть доступным ко времени, когда VisitorInter() или что-либо еще, для которого требуется IP-адрес, называется.

class OnlineVisitors {
  constructor() {
    this.ipPromise = this.fetchIP();
    // redis stuff elided from example
  }
  async fetchIP() {
    const resp = await axios.get("https://api.ipgeolocation.io/getip");
    return resp.data.ip;
  }
  async VisitorInter() {
    const ip = await this.ipPromise;  // this could potentially hang forever if ipgeolocation.io doesn't feel like answering
    console.log(ip);
  }
};

module.exports = new OnlineVisitors();
...