简体   繁体   中英

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);
  })

});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM