当我尝试从我的任何异步函数中为猫鼬服务返回值时,我一直遇到问题。
发生的事情是它永远不想返回值,在大多数情况下只提供了未定义的值,这使我不知道这里发生了什么。我对这种事情还很陌生,所以可以伸出援手的人将是上帝的救赎。
如果我在getBalance函数中记录该值,则它工作得很好,并且余额显示为预期值。
async getBalance(username) {
await users.find({username: username}, function(err, res) {
return(res[0].balance);
});
}
下面的代码是我使用该函数的方式,我等待结果(始终未定义)。
async removeCoins(username, amount) {
var coins = await parseInt(this.getBalance(username));
coins -= amount;
await users.updateOne({ username: username }, { balance: coins }, function(err, result) {
if (err) { console.log(err); return false; }
return true;
});
}
结果是出现以下错误:CastError: Cast to Number failed for value "NaN" at path "balance"
在此方面提供任何帮助,以帮助我为什么根本没有获得返回值的任何帮助将不胜感激。如前所述,如果我将余额记录在get balance函数中,它将获得很好的功能。
答案 0 :(得分:2)
这是因为await
等待诺言的解决方案,而不是回调。像这样使用sth:
async getBalance(username) {
return new Promise((resolve, reject) => {
users.find({username: username}, (err, res) => {
if (err) return reject(err);
resolve(res);
});
});
}
async removeCoins(username, amount) {
// parseInt the result, not the waiting promise
let coins = parseInt(await this.getBalance(username));
return new Promise((resolve, reject) => {
users.updateOne({ username: username }, { balance: coins }, (err, result) => {
if (err) return reject(err); // or console.warn it
resolve(result);
}
});
}
然后在您称为removeCoins的某个地方
removeCoins(username, amount)
.then(() => { ... }) // callback after coins removed
.catch(err => console.warn(err));
// or simply await the function and catch possible errors later
await removeCoins(username, amount);