【发布时间】:2023-04-09 14:27:01
【问题描述】:
我正在尝试通过在实例化类时调用方法来缓存从 Node.js 中的类中的 get 请求接收到的数据。我只想在创建类的新实例时运行一次。
class GetSomeData {
constructor() {
this.storedData = '';
this.getData();
}
getData = async () => {
const allData = await axios.get(`URL`, config)
this.storedData = allData
}
}
let newInstance = new GetSomeData();
当我记录 newInstance.storedData 我得到''。 我正在从 get 请求接收数据,但无法将其存储在 this.storedData 中。
由于某种原因,这可行:
class GetSomeData {
constructor() {
this.storedData = this.getData();
}
getData = async () => {
const allData = await axios.get(`URL`, config)
return allData
}
}
let newInstance = new GetSomeData();
当我记录 newInstance.storedData 时,我得到了实际数据。
第二种方法应该在我每次访问 newInstance.storedData 时运行 getData 方法,但实际上它只在创建新实例时运行一次。 我不明白我错过了什么。
【问题讨论】:
标签: javascript node.js class methods constructor