0

After going through simple examples on cloud functions that worked, I want to test something more complex. I have created a table (BTDevices) table in the Firebase realtime database, populated with few data:

enter image description here

Now I want my cloud function to use the MAC addresses for retrieving the "userId" fields. This is a snippet of my JavaScript cloud function:

var getUserIdPromisesArray = [];

for (var i = 0; i < nearbyMACsArray.length; i++) {
  var tmpNearbyMAC = nearbyMACsArray[i];
  var promise = admin.database().ref(`${DB_BT_DEVICES}/${tmpNearbyMAC}/userId`).once('value');
  getUserIdPromisesArray.push(promise);
}

return Promise.all(getUserIdPromisesArray).then(results => {
  results.forEach(result => {
    var userId = result.val();
    console.log('result.val() = ', result.val());
  });
});

From other posts like this, this, and this, I know that I need to first create all my promises, and when they are done, then process the fetched data. So the for-loop iterates the nearbyMACsArray that contains the MAC addresses, creates a promise, and pushes it to the getUserIdPromisesArray.

Then I wait for all promises to finish and iterate the "results" array to print the read value, but the cloud function log shows a null value in one of the outputs:

output log

Any ideas on why this is happening? Am I missing something with the promises? Thanks.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Dimitris
  • 419
  • 4
  • 19

1 Answers1

1

According to the documentation, val() returns null when there is no data at the requested location. This is most likely what's going on. It's not likely a problem with your promises.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Thanks Doug for the fast reply, indeed there was an issue with the populated data, and they were not actually in the database! – Dimitris Jun 14 '19 at 15:49