Search code examples
reactjstypescriptpromisees6-promise

To retrieve a value in a Promise


I have a method like this, and I want to fill teamMems array. What am I doing so wrong!

takeTeamMembers(client:any, teamIds:string[], projectId:string){
        
    var teamMems :TeamMember[] = []
    teamIds.forEach((teamId:string) =>{
        client.getTeamMembersWithExtendedProperties(projectId, teamId, undefined, undefined).then(
            function(items:any){
                items.map((curr:any) => {
                    if(teamMems.filter((item:TeamMember) => {return item.memberId == curr.identity.id}).length == 0){
                        teamMems= [...teamMems, {teamIds: [teamId], memberId:curr.identity.id, name:curr.identity.displayName}]
                    }
                    else{
                        teamMems.filter((item:TeamMember)=> item.memberId == curr.identity.id)[0].teamIds.push(teamId);
                    }
                })
                console.log("1 return innermems", teamMems)
            });
            console.log("2 return ", teamMems)
        })
        console.log("before return ", teamMems)
        return teamMems;
}

Console output is

enter image description here


Solution

  • I think you'll have a better time with an async function like this. The idea is to use Promise.all() to first await for all of the getTeamMembersWithExtendedProperties calls, and then just work on the flat, regular array.

    // dummy implementation to ensure types are correct, replace with your actual stuff
    async function getTeamMembersWithExtendedProperties(projectId: string, teamId: string) {
      return ["something"];
    }
    
    async function takeTeamMembers(client: any, teamIds: string[], projectId: string) {
      const teamsAndMembers = await Promise.all(
        teamIds.map(async (teamId) => ({
          teamId,
          members: await getTeamMembersWithExtendedProperties(projectId, teamId),
        })),
      );
      const teamMems = [];
      const innerMems = [];
      teamsAndMembers.forEach(({ teamId, members }) => {
        // Do the innerMems/teamMems logic here...
      });
      return teamMems;
    }