首页 > 解决方案 > 在类中使用 fetch 函数?

问题描述

即使它存在于 json 文件中,它也会返回weightas 。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)
})()

标签: javascriptclassasync-awaitfetch

解决方案


您可以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);
    });
})()


推荐阅读