gpt4 book ai didi

javascript - 从 Firebase 数据库中的两个 promise 中获取结果

转载 作者:行者123 更新时间:2023-11-29 19:03:26 24 4
gpt4 key购买 nike

我的 Firebase Web 应用程序中有下一个功能:

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 的总和,然后返回两个结果的差值。

问题(显然)是 promises ¿我怎样才能正确地做到这一点?

最佳答案

你可以使用async/await,从.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

关于javascript - 从 Firebase 数据库中的两个 promise 中获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45023658/

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