gpt4 book ai didi

javascript - 移相器/类型错误 : Cannot read property 'then' of undefined

转载 作者:行者123 更新时间:2023-12-03 01:33:01 26 4
gpt4 key购买 nike

在我的游戏中,我想保存用户更新的分数,然后从数据库中检索排名。我知道 Promise 是必经之路,而且我已经在 Stack Overflow 上尝试了很多答案,但我不明白为什么会出现以下错误:

TypeError: Cannot read property 'then' of undefined

通过此函数,我可以更新用户的分数:

saveScoreOnDb: function () {
var self = this;

if(!this.scoreUpdated && (this.score > this.game.global.currentUser.high_score)){
// do this just once
this.scoreUpdated = true;

return new Promise(function (resolve, reject) {
// save current score on Db
var xhttp = new XMLHttpRequest();
xhttp.open("PUT", "https://myproject.herokuapp.com/api/users/" + self.game.global.currentUser.id, true);
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var input = JSON.stringify({
'high_score': self.score
});

xhttp.onload = function(){
if (xhttp.readyState == XMLHttpRequest.DONE && xhttp.status == 200){
console.log('resolved the savetoDB thingy');
resolve(xhttp.response);
}
};
xhttp.onerror = function(){
reject(xhttp.statusText);
};

xhttp.send(input);
});
} else {
self.getRankingFromDb();
}
}

在另一个函数中,在开关内,我使用以下代码调用该函数:

this.saveScoreOnDb().then(function(reply){
console.log('promise: ', + reply);
self.getRankingFromDb();
});

这种情况出了什么问题?

最佳答案

你需要始终返回一个 promise 。 Promise 可以是虚拟文本、nullundefinedvoid 等。您可以选择,但需要始终返回一个 Promise 才能使用.then().catch()

所以在这里我只是将 Promise 移到了 if 上方几行,并做了 else resolve (否则你永远不会解析如果您输入if)。如果您愿意,您也可以拒绝它。

您还需要将 this 替换为 self

saveScoreOnDb: function () {
var self = this;

return new Promise(function (resolve, reject) {
if (!self.scoreUpdated && (self.score > self.game.global.currentUser.high_score)) {
// do this just once
self.scoreUpdated = true;

// save current score on Db
var xhttp = new XMLHttpRequest();
xhttp.open("PUT", "https://myproject.herokuapp.com/api/users/" + self.game.global.currentUser.id, true);
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var input = JSON.stringify({
'high_score': self.score
});

xhttp.onload = function () {
if (xhttp.readyState == XMLHttpRequest.DONE && xhttp.status == 200) {
console.log('resolved the savetoDB thingy');
resolve(xhttp.response);
}
};
xhttp.onerror = function () {
reject(xhttp.statusText);
};

xhttp.send(input);
} else {
resolve(self.getRankingFromDb());
}
});
}

关于javascript - 移相器/类型错误 : Cannot read property 'then' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51195985/

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