【发布时间】:2021-02-16 07:01:41
【问题描述】:
我有一个要执行的脚本。我需要脚本,按下提交按钮:
- 从 Google Firestore 中获取值
- 在计算中使用这些值
- 使用此计算的结果写回 Firestore 数据库
我已将console.log("eff[1,2,3]" + result of calculation) 用于帮助在控制台日志中跟踪执行顺序。它首先显示eff3,然后是eff1,然后是eff2,所以这意味着提交给firestore的值为零(因为它是在计算之前)计算确实计算出正确的答案它只是没有将答案提交给数据库。
如何更改我的代码以使其以正确的顺序执行?
// Triggered when the send new message form is submitted.
function onMessageFormSubmit(e) {
e.preventDefault();
//Calculate efficiency
var preodo = 0
var efficiency = 0
firebase.firestore().collection('Vehicle').doc(reg.value).collection('Refuels').orderBy('Date', 'desc').limit(1)
.onSnapshot(function(snapshot) {
snapshot.docChanges().forEach(function(change) {
preodo = change.doc.data().Odometer
efficiency = (odo.value - preodo) / amount.value
efficiency = efficiency.toFixed(4);
console.log("eff1:" + efficiency)
});
console.log("eff2:" + efficiency)
});
//Save refuel transaction with all details form the form as well as the calculated efficiency
console.log("eff3:" + efficiency)
saveMessage(reg.value, odo.value, date.value, amount.value, price.value, rebate.value, efficiency).then(function() {
window.alert('Refuel submitted!')
// Clear message text field and re-enable the SEND button.
resetMaterialTextfield();
toggleButton();
});
}
【问题讨论】:
-
我的猜测是,从未使用过 Google Firestore,
onsnapshot方法是异步的,但您的代码正在以同步方式运行savemessage方法。能否在onSnapshot方法中添加Promise并使用解析后的值继续程序流程? -
你能不能把
saveMessage代码上移到“eff2”行之后? -
@carljdp,如果我这样做了,它会多次提交保存,就好像它在循环中一样
-
@JillianWittstock,我明白了。我没有更多建议(目前),perhaps this can be helpful 在进一步调试中。
标签: javascript html google-cloud-firestore