我的WebApp with Firebase中有下一个功能:
function loadMonthData(){
let ganancias = 0;
let perdidas = 0;
let thisMonth = new Date();
thisMonth.setHours(0);
thisMonth.setMinutes(0);
thisMonth.setMilliseconds(0);
thisMonth.setDate(1);
fireIngresos.orderByChild('timestamp')
.startAt(thisMonth.getTime())
.once('value')
.then((snapshot)=>{
snapshot.forEach((ingreso)=>{
ganancias += ingreso.val().cash;
});
});
fireGastos.orderByChild('timestamp')
.startAt(thisMonth.getTime())
.once('value')
.then((snapshot)=>{
snapshot.forEach((perdida)=>{
perdidas += perdida.val().cash;
});
});
return ganancias - perdidas;
}
这得到我的引用fireIngresos和FireGastos中所有元素的属性cash
的总和(从月初开始),然后返回两个结果的差异。
问题(显然)是承诺¿我怎样才能正确地做到这一点?
答案 0 :(得分:3)
您可以使用return
,.then()
来自async function loadMonthData(){
let ganancias = 0;
let perdidas = 0;
let thisMonth = new Date();
thisMonth.setHours(0);
thisMonth.setMinutes(0);
thisMonth.setMilliseconds(0);
thisMonth.setDate(1);
return await fireIngresos.orderByChild('timestamp')
.startAt(thisMonth.getTime())
.once('value')
.then(snapshot => {
snapshot.forEach(ingreso => {
ganancias += ingreso.val().cash;
});
return ganacias
})
- await fireGastos.orderByChild('timestamp')
.startAt(thisMonth.getTime())
.once('value')
.then(snapshot => {
snapshot.forEach(perdida => {
perdidas += perdida.val().cash
});
return peridadas
});
}
loadMonthData().then(result => {// do stuff with result});
function promise(n) {
return new Promise(resolve =>
setTimeout(resolve, Math.floor(Math.random() * 1000), n)
).then(data => data)
}
async function diff() {
return await promise(2 * 4) - await promise(2 * 2);
}
diff().then(res => console.log(res)); // 4
UIView