我是javascript的初学者,最近我一直在从事一个项目,在这个项目中,我试图将初始得分保存在一个空的Firebase数据库中,该数据库工作得很好。但是,就像保存分数一样,我想检索它并对其进行一些计算。我已经尝试过setTimeout
,但是没有用。顺便说一句,如果火力计中已经有分数,那就可以了。
这是我的代码,在此先感谢:
function resultOne() {
var firstScore = trim(newGroup[0]);
scores(firstScore);
setTimeout(function() {return true;}, 30000);
var firstguyScore = getScore(firstScore)
console.log(firstGuyScore);
}
此功能可以设置初始分数1500并设置名称...。
function scores(firstGuy) {
// Firebase query to increment the chosen girl and her seen status by 1 and to initialize each score by 1500
let ref = firebase.database().ref("scores");
let query = ref.orderByChild("name").equalTo(firstGuy);
query.once("value").then((snapshot) => {
if (snapshot.exists()) {
snapshot.forEach((userSnapshot) => {
let userRef = userSnapshot.ref;
userRef.child("chosen").transaction((currentValue) => {
return currentValue + 1;
});
userRef.child("seen").transaction((currentValue) => {
return currentValue + 1;
});
});
}
else {
ref.push({
name: firstGuy,
chosen: 1,
seen: 1,
score: 1500
});
}
});
这是检索数据的功能
async function getScore(firstGuy) {
let ref = firebase.database().ref("scores");
let query = ref.orderByChild("name").equalTo(firstGuy);
const snapshot = await query.once("value")
if (snapshot.exists()) {
snapshot.forEach((userSnapshot) => {
var userData = userSnapshot.val();
score = userData.score;
console.log(score);
});
}
}
答案 0 :(得分:0)
setTimeout()
在一段时间后调用您提供的函数(回调)。它不会阻止并等待。您在控制台中看到的对getScores()
的调用会立即执行。
您可以按以下方式更改代码:
function resultOne() {
const firstScore = trim(newGroup[0]);
scores(firstScore);
setTimeout(() => {
const firstguyScore = getScore(firstScore);
console.log(firstGuyScore);
}, 30000);
}
以这种方式使用setTimeout()
可以进行测试和调试。您不应在可用于生产的代码中以这种方式使用它。
为什么await
上的scores()
也没有?
async function scores(firstGuy) {
...
const snapshot = await query.once("value");
...
}
async function resultOne() {
const firstScore = trim(newGroup[0]);
await scores(firstScore);
const firstguyScore = await getScore(firstScore);
console.log(firstGuyScore);
}