简体   繁体   中英

How to call sendToDevice multiple times as a function result?

I have a Firebase Cloud Functions script where I would like to send push notifications to users. When I only send one time to a specified set of token array, which is returned by a function, it's working properly:

return getTokens(array1).then(tokens => {
  return (admin.messaging().sendToDevice(tokens, payload));
});

However I can't seem to figure out how to do this multiple times with different inputs to the getTokens function. I would need to do something like this:

return getTokens(array1).then(tokens => {
  return (admin.messaging().sendToDevice(tokens, payload));
});

return getTokens(array2).then(tokens => {
  return (admin.messaging().sendToDevice(tokens, payload));
});

Of course the above mentioned solution fails because the second return then pair is unreachable code but I cannot figure how to do this properly in JavaScript.

How can this be handled in a smooth way? Please excuse me in advance, if I'm asking something obvious, I'm pretty new to JavaScript.

EDIT

I tried the following code:

    Promise.all([getTokens(inputArray1), getTokens(inputArray2)]).then(results => {
        const tokens1 = results[0].val();
        const tokens2 = results[1].val();
        const promises = [];
        promises.push(admin.messaging().sendToDevice(tokens1, payload));
        promises.push(admin.messaging().sendToDevice(tokens2, payload));
        return Promise.all(promises);
    });

It produces the following error: Expected catch() or return

This is how you do it:

return Promise.all([admin.database().ref(`/tokensArray1`).once('value'), admin.database().ref(`tokensArray2`).once('value')]).then(results => {
  const tokensArray1 = results[0].val();
  const tokensArray2 = results[1].val();
  const promises = [];
  let payload = {
    notification: {
      title: 'title',
      body: 'msg',
      icon: 'default'
    }
  };
  promises.push(admin.messaging().sendToDevice(tokensArray1, payload));
  promises.push(admin.messaging().sendToDevice(tokensArray2, payload));
  return Promise.all(promises);
});

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