从Firebase数据库中的两个承诺中获取结果

时间:2017-07-11 00:45:43

标签: javascript firebase firebase-realtime-database promise

我的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的总和(从月初开始),然后返回两个结果的差异。

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

1 个答案:

答案 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