我正在使用async / await对数据库进行查询并获取结果,但是我不知道为什么在浏览器控制台中会出现此错误:
未处理的承诺拒绝TypeError:“游戏未定义”
我有两个函数,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();
};
在浏览器控制台中,我得到了以下结果:
为什么不在这里异步/等待工作?我究竟做错了什么?
最佳答案
您只是忘记了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/