0

I have this code below that I uploaded as a firebase function. whenever I checked the logs using firebase functions:log, I can see that the expoTokens array is empty.

var expoTokens = [];

db.collection('members').get()
.then(docs => {

   var data = []

   docs.forEach(doc => {
      if (recipients.includes(doc.id)) {
         doc.data().expoTokens.forEach(token => {
            if (!data.includes(token)) data.push(token);
         })
      }
   })

   return Promise.all(data);
})
.then((data) => {
   expoTokens = data;
})

console.log("expoTokens");
console.log(expoTokens);

What I only need is to get an array of ExpoTokens so I can send notification.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Nats E
  • 53
  • 2
  • 6

2 Answers2

1

I would recommend to use asyc/await to make the code flow more clear. Your functions could be written like this:

var expoTokens = [];

const docs = await db.collection("members").get();

var data = [];

docs.forEach((doc) => {
  if (recipients.includes(doc.id)) {
    doc.data().expoTokens.forEach((token) => {
      if (!data.includes(token)) expoTokens.push(token);
    });
  }
});

console.log("expoTokens");
console.log(expoTokens);

// TO DO
// Send notifications using expoTokens using await

// We return to let the cloud function know that we are done
return;

Just don't forget the async in your function like async (snap, context) => {}

Tarik Huber
  • 7,061
  • 2
  • 12
  • 18
0

Your console.log(expoTokens); happens before expoTokens = data; ever runs.

See:

If you want to return the expo tokens out of the Cloud Function, return them from inside then upwards and out of the main function:

return db.collection('members').get().then(docs => {
   var data = []

   docs.forEach(doc => {
      if (recipients.includes(doc.id)) {
         doc.data().expoTokens.forEach(token => {
            if (!data.includes(token)) data.push(token);
         })
      }
   })

   return Promise.all(data);
})
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807