Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在类中使用fetch函数?_Javascript_Class_Async Await_Fetch - Fatal编程技术网

Javascript 在类中使用fetch函数?

Javascript 在类中使用fetch函数?,javascript,class,async-await,fetch,Javascript,Class,Async Await,Fetch,它将权重返回为未定义,即使它存在于json文件中。即使我将权重设置为空对象,例如构造函数中的this.weight=',它也只会记录一个空字符串。有什么帮助吗 class口袋妖怪{ 建造师(姓名){ this.name=name this.init() } 初始化=()=>{ 取回(`https://pokeapi.co/api/v2/pokemon/${this.name}`) .then(response=>response.json()) 。然后(数据=>{ this.name=data.

它将
权重
返回为
未定义
,即使它存在于json文件中。即使我将权重设置为空对象,例如构造函数中的
this.weight='
,它也只会记录一个空字符串。有什么帮助吗

class口袋妖怪{
建造师(姓名){
this.name=name
this.init()
}
初始化=()=>{
取回(`https://pokeapi.co/api/v2/pokemon/${this.name}`)
.then(response=>response.json())
。然后(数据=>{
this.name=data.name
this.weight=data.weight
this.height=data.height
this.move=data.moves[0].move.name;
})
}
}
(异步()=>{
const pika=新口袋妖怪(“皮卡丘”);
控制台.日志(等待pika.高度)
})()

您可以让
init
返回其承诺,并且让
init
不是从构造函数调用,而是由
口袋妖怪的调用方调用:

class口袋妖怪{
建造师(姓名){
this.name=name
}
初始化=()=>{
回传(`https://pokeapi.co/api/v2/pokemon/${this.name}`)
.then(response=>response.json())
。然后(数据=>{
this.name=data.name
this.weight=data.weight
this.height=data.height
this.move=data.moves[0].move.name;
})
}
}
(异步()=>{
const pika=新口袋妖怪(“皮卡丘”);
pika.init()
.然后(()=>{
控制台.日志(pika.高度);
});

})()
谢谢,它成功了!