Search code examples
javascriptes6-promise

Pass array in promise chain


I'm trying to send notifications for all guests who are invited to an event.

The below code works up to the console.log(guestPlayerIds); which returns undefined. What is the best way to pass guestPlayerIds?

exports.sendNewEventFcm = functions.database.ref('/fcm/{pushID}').onWrite(event => {

  const eventID = event.params.pushID;
  const dsnap = event.data.val();

  // Exit when the data is deleted.
  if (!event.data.exists()) {
    return;
  }

  let guests = Object.keys(dsnap);

  const promises = guests.map((data) => admin.database().ref('playerIds').child(data).once('value'));

  return Promise.all(promises).then(data => {

    let guestPlayerIds = [];

    let returns = data.map(item => {
      let itemVal = Object.keys(item.val())[0];
      console.log(Object.keys(item.val())[0])
      guestPlayerIds.push(itemVal);

    });
  }).then(guestPlayerIds => {
    console.log(guestPlayerIds);
  })

});

Solution

  • Using map is good, but you should return something inside the callback, and then also return the result of the overall map:

    return data.map(item => {
      let itemVal = Object.keys(item.val())[0];
      console.log(Object.keys(item.val())[0])
      return itemVal;
    });
    

    You actually don't need the array variable guestPlayerIds at that point. Only in the subsequent then you can use it like you already had it.