Reputation: 169
I'm trying to create a function in node js which reads database values in a for loop and pushes them into an array, and then at the end returns this array. My functions looks like this at the moment:
function loadTokens(userIds) {
var tokens = [];
userIds.forEach(item => {
admin.database().ref('/users/' + item).once('value').then(snapShot => {
var user = snapShot.val();
console.log('User', user.name);
console.log('token', user.fcmToken);
return tokens.push(user.fcmToken);
};
});
return tokens;
}
In the main part of the code I would like to call this funtion and use a .then to get the returned array and call another funtion which takes the array as a parameter. I would like to do this to ensure that the array is filled when passed as a parameter.
return loadTokens(userIds).then(tokens => {
console.log('tokens', tokens)
return admin.messaging().sendToDevice(tokens, payload);
});
I did some research and I learned that I would have to return a Promise in my function which somehow contains the array so it can be used in a .then statement.
Can you help me out how I can return a promise in the function and how will the array be accessible in the .then part?
Upvotes: 0
Views: 1072
Reputation: 599776
Something like this should do the trick:
function loadTokens(userIds) {
var promises = userIds.map(item => admin.database().ref('/users/' + item).once('value'));
return Promise.all(promises).then(snapshots => {
return snapshots.map(snapshot => snapshot.val().fcmToken);
});
}
So we're using Promise.all()
to wait for all tokens to be loaded, and return the token from our then
completion handler.
Upvotes: 1