gpt4 book ai didi

javascript - 未处理的 promise 拒绝 TypeError

转载 作者:行者123 更新时间:2023-11-30 19:30:50 25 4
gpt4 key购买 nike

我正在使用 async/await 查询数据库并获取结果,但我不知道为什么浏览器控制台会出现此错误:

Unhandled promise rejection TypeError: "games is undefined"

我有两个函数,异步的 getData 和调用 getGames:

getGames(){
let query = HOMELF1_NEXT_GAMES;
var data = {
"query": query,
"variables": null
}
fetch(URL_FEB_API, {
method: "POST",
headers: {
"Accept" : "application/json",
"content-type" : "application/json"
},
body: JSON.stringify(data)
})
.then(response => {
return response.json()
})
.then(data => {
console.log("End query");
return data;
})
.catch(err => {
console.log("Error: " + err)
})
}

async getData(){
console.log("Before getGames");
let games = await this.getGames();
console.log("After getGames");
console.log("games: " + games.length)
}

componentDidMount(){
this.getData();
};

在浏览器控制台中我得到了这个结果:

enter image description here

为什么不在这里工作 async/await?我做错了什么?

最佳答案

你刚刚忘记了return

getGames(){
let query = HOMELF1_NEXT_GAMES;
var data = {
"query": query,
"variables": null
}
\/ here
return fetch(URL_FEB_API, {
method: "POST",
headers: {
"Accept" : "application/json",
"content-type" : "application/json"
},
body: JSON.stringify(data)
})
.then(response => {
return response.json()
})
.then(data => {
console.log("End query");
return data;
})
.catch(err => {
console.log("Error: " + err)
})
}

async getData(){
console.log("Before getGames");
let games = await this.getGames();
console.log("After getGames");
console.log("games: " + games.length)
}

componentDidMount(){
this.getData();
};

关于javascript - 未处理的 promise 拒绝 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56442798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com