MGR Programming
MGR Programming

Reputation: 655

Wait till list of Firebase reads are completed before returning an array of records

I want to use an amp-list with firebase functions. I need to wait, till several records are assembled in the array, before I return it.

Here the code that I used so far (not working due to asynchronous db read):

app.get('/favorites', (req, res)=>{
    const user.favorites = {
        '-KCyK9E3aQNe6fnjYrF6': {added:'2018-04-23'},
        '-KCyK9E3aQNe6fnjYrF7': {added:'2018-04-22'}
    };
    let data = []
    for (var key in user.favorites) {
        if (user.favorites.hasOwnProperty(key)){
            admin.database().ref('/records/'+key).once('value',snapshot=>{
                const record = snapshot.val();
                console.log(record.name); //works o.k.
                data.push(record);
            })
        }
    }
    res.send(data); //returns []
})

How do I need to improve it (count all reads and then exit & res.send(data))?

Upvotes: 0

Views: 46

Answers (1)

MuruGan
MuruGan

Reputation: 1420

use promise.all to wait for promises to return the snapshot. for ex see the below code for sample.

let data = [];
let allDataPromises =[]; // going to the push the promises into this array
for (var key in user.favorites) {
    if (user.favorites.hasOwnProperty(key)){
       allDataPromises.push(admin.database().ref('/records/'+key).once('value')); // returns the promise
    }
}

if(allDataPromises.length>0){
    return Promise.all(allDataPromises).then(function (snaps){
        snaps.forEach(function(s){
            const record = s.val();
            console.log(record.name); //works o.k.
            data.push(record);
        });

        if(data.length>0){
           return res.status(200).send(data);
        }else {
           return res.status(400).send('{message:"No Record Found"}');
        }            
    });
}
else{
  return res.status(400).send('{message:"No Promises Found"}');
}

Upvotes: 2

Related Questions