Why does returning snapshot.val() in a Promise whe

2019-08-03 08:34发布

问题:

I'm writing a Firebase Cloud Function and I'm trying to figure out how Promise.all works. In my code, I pass in an array of database queries and I'm trying the read the resulting array, but I'm only getting garbage:

T {
  A: 
   P {
     k: Sb { Ka: [Function: vb], ba: [Object] },
     aa: P { k: [Object], aa: null, wb: [Object], Bb: '' },
     wb: Zc { ld: [Object], ac: [Object] },
     Bb: null },
  V: 
   R {
     u: 
      Gd {
        app: [Object],
        L: [Object],
        Ua: [Object],
        Sc: null,
        ca: [Object],
        td: 1,
        Qa: [Object],
        va: [Object],
        qg: [Object],
        jc: [Object],
        ee: [Object],
        md: [Object],
        ia: [Object],
        Xa: [Object],
        cd: 2,
        fe: null,
        K: [Object] },
     path: J { o: [Object], Y: 0 },
     m: 
      Df {
        xa: false,
        ka: false,
        Ib: false,
        na: false,
        Pb: false,
        oa: 0,
        kb: '',
        bc: null,
        xb: '',
        Zb: null,
        vb: '',
        g: Tc {} },
     Kc: false,
     then: undefined,
     catch: undefined },
  g: Tc {} }

I'm expecting a simple json:

{
    "name": "Foo",
    "number": 2521
    // And a few other fields
}

BTW, I watched Jen's video so I know what I'm doing is wrong anyway; I just want to know why my existing code doesn't work. (I haven't tested it, but I believe the solution is to return the raw snapshots in my db query and then do the .val() call.)

Relevant code if the links disappear:

function mergeTeams(duplicates) {
    return Promise.all([
        admin.database().ref(someRef).once('value', (snap) => {
            return snap.val();
        }),
        admin.database().ref(someRef2).once('value', (snap) => {
            return snap.val();
        })
    ]).then(values => {
        console.log(values);

        const team1 = values[0];
        const team2 = values[1];
        console.log(team1);
        console.log(team2);
}

回答1:

So, here's the code that works (and the explanation below):

return Promise.all([
    admin.database().ref(teamRef + duplicates.teamKey1).once('value'),
    admin.database().ref(teamRef + duplicates.teamKey2).once('value')
]).then(values => {
    const team1 = values[0].val();
    const team2 = values[1].val();

    console.log(team1);
    console.log(team2);
});

The reason it works is because I've always getting the promises in the values array even though I didn't know it. Here's what Promise.all returns: an array with the raw result of the promises passed in. When I was returning stuff inside the success callback, that didn't actually do anything because it wasn't part of the promise; I was just returning random stuff to an empty void. And when I was printing the teams, I was actually logging the Firebase Snapshot object instead of the .val().