【问题标题】:Use fetch function within a class?在类中使用 fetch 函数?
【发布时间】:2020-12-10 12:02:54
【问题描述】:
它会将weight 作为undefined 返回,即使它存在于 json 文件中。即使我将重量设为空对象,例如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)
})()
【问题讨论】:
标签:
javascript
class
async-await
fetch
【解决方案1】:
你可以让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);
});
})()