Renji
Renji

Reputation: 310

Multiple Database Calls in Cloud functions

I have a callable Cloudfunction that should fetch multiple data. The keys where to fetch from are calculated by the function.

I have an array like this

var keys = ["key1", "key2, "key5"]

The problem is that the length of the keylist is variable and i want to send all the datas gathered from the database at the given key back to the user.

Something like this:

result = {
  key1: value,
  key2: value,
  key5: value,
}

The database only gives out Promisses that are not asnyc. How do I make sure that i only give out data, once all the data are gathered. Something like

admin.database().ref('/path/key1').once('value').then( snapshot => {
  admin.database().ref('/path/key2').once('value').then ( snapshot => {
    ...
  }
}

Won't work, because the number of keys is variable.

Upvotes: 0

Views: 540

Answers (1)

Renji
Renji

Reputation: 310

I managed to find a solutoion to my Problem

I had to write a recursive function to chain the promises

function fetchData(keyArray) {
  var index = 0;
  var fetchedValues = {};

  return new Promise(function(resolve, reject) {
    function next(fetchedValues) {
      if (index < keyArray.length) {
        newFetchedValues = fetchedValues;
        admin.database().ref('/path/to/key/' + keyArray[index]).once('value').then(((snapshot) => {
          newFetchedValues[keyArray[index]] = snapshot.val();
          index++;
          next(newFetchedValue);
        }), reject);
      } else {
        resolve(fetchedValues);
      }
    }
    next(fetchedValues);
  });
}

This function returnes a promise object, that can states resolved, once all the Values in the array are Fetched. This allows synchronous Fetching of a dynamic number of Values.

I solved this by following the first answer of this question How to synchronize a sequence of promises?

Upvotes: 1

Related Questions