javascript - 如何将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' }
解决方案
您正在将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();
推荐阅读
- c++ - 在这个有效的斐波那契函数中,它不是传递可以存储在数组中的元素数量吗?
- android - Android SQLite - Update table 1 based on changes in table 2
- java - Parsing JSON File using Gson
- ios - 如果输入为空,如何按 ALL 过滤?SwiftUI/核心数据
- powerbi - 如何在 Power BI 嵌入式代码中实现安全性?
- c++ - Qt StyleSheet to programmatically createdQWidget
- java - 在不使用 InputStream 的情况下更新 Java Apache POI 中的现有 Excel 文件
- c# - DateTime 到 DateTimeOffset 的 EF Core 迁移
- python - 当 assertEqual 抛出异常时如何向用户显示消息?
- algorithm - Haskell中抽象图的DFS实现