javascript - 在类中使用 fetch 函数?
问题描述
即使它存在于 json 文件中,它也会返回weight
as 。undefined
即使我将权重设为空对象,例如this.weight = ''
在构造函数中,它也只会记录一个空字符串。有什么帮助吗?
class Pokemon {
constructor(name){
this.name = name
this.init()
}
init = () => {
fetch(`https://pokeapi.co/api/v2/pokemon/${this.name}`)
.then(response => response.json())
.then(data => {
this.name = data.name
this.weight = data.weight
this.height = data.height
this.move = data.moves[0].move.name;
})
}
}
(async () => {
const pika = new Pokemon('pikachu');
console.log(await pika.height)
})()
解决方案
您可以init
返回它的 Promise,并且init
不是从构造函数调用,而是由调用者调用Pokemon
:
class Pokemon {
constructor(name){
this.name = name
}
init = () => {
return fetch(`https://pokeapi.co/api/v2/pokemon/${this.name}`)
.then(response => response.json())
.then(data => {
this.name = data.name
this.weight = data.weight
this.height = data.height
this.move = data.moves[0].move.name;
})
}
}
(async () => {
const pika = new Pokemon('pikachu');
pika.init()
.then(() => {
console.log(pika.height);
});
})()
如果它需要在多个地方使用,并且init
不适合在外部调用,您还可以让构造函数将 Promise 分配给一个实例属性并链接它:
class Pokemon {
constructor(name){
this.name = name
this.init();
}
init = () => {
this.initProm = fetch(`https://pokeapi.co/api/v2/pokemon/${this.name}`)
.then(response => response.json())
.then(data => {
this.name = data.name
this.weight = data.weight
this.height = data.height
this.move = data.moves[0].move.name;
})
}
}
(async () => {
const pika = new Pokemon('pikachu');
pika.initProm
.then(() => {
console.log(pika.height);
});
})()
推荐阅读
- arduino - 我需要 malloc C 风格的字符串吗?
- jestjs - 执行测试时错误套接字隧道
- python - 如何将日志文件解析为对象列表
- javascript - 角喷射器
- powershell - Sharepoint在线powershell用户自定义操作脚本块不起作用
- node.js - 有没有办法从电脑模拟 Beacon 并在同一台电脑上接收它?
- netsuite - NetSuite CSV 响应文件
- maven - Intellij Idea(2020.1) 是否删除了 maven 自动导入依赖项?
- google-chrome-extension - 在邮递员中模仿 chrome 下载请求
- autodesk-forge - 如何确定已发布工作共享 Revit 模型的语言集?