I'm using Parse's Cloud Code to write a method that will return and array containing two sub arrays. With on array being an array of teams and the other being an array containing arrays of those team members. With the purpose of getting a list of teams and their team members. The arrays will be passed to an iOS front end to display.
My data is currently structured so that there is a Team object that can have multiple Users but a User can only have one team.
Here's my cloud function as it lives now:
var arrayOfUsers = [];
var arrayOfTeamMembers = [];
var arrayOfTeams = [];
Parse.Cloud.define("GetTopTeams", function(request, response) {
var query = new Parse.Query("Teams");
arrayOfTeams = [];
arrayOfTeamMembers = [];
fullArray = [];
query.find().then(function(teams) {
//returns a raw list of teams
return teams;
}).then(function(teams) {
arrayOfUsers = [];
teams.forEach(function(team) {
//add team to subArray1
arrayOfTeams.push(team);
//searches for all users within the team
var memberQuery = new Parse.Query(Parse.User);
memberQuery.equalTo('team', team);
memberQuery.find().then(function(tMember) {
//adds the team member to initial array
arrayOfUsers.push(tMember);
});
}).then(function(){
//pushes the finished array to the team member array
return arrayOfTeamMembers.push(arrayOfUsers);
}).then(function() {
return arrayOfTeams;
});
}).then(function() {
return response.success([arrayOfTeams, arrayOfTeamMembers]);
});
});
I'm able to populate the arrayOfTeams but getting the arrayOfTeamMembers is proving to be difficult. Is there a better way to nest them? I tried promises but am unfamiliar with Javascript promises. I've found similar posts but none that address the issue I'm having. Any suggestions?