首页 > 解决方案 > 如何将promise对象转换为类中的对象

问题描述

我想用 axios 从我的项目外部获取数据。我在课堂上这样做,但由于某种原因,我在 promise 对象中检索数据,我使用 await 和 promise,但最终我在 [object promise] 中接收数据。

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' }

标签: javascriptclasspromiseasync-await

解决方案


您正在将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();

推荐阅读