Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
push in forEach not working with async function

So I am trying to push objects into an array. If I console.log() the objects are being printed into console. So they are not undefined. But if I try to push them, it says: "Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'push')".

Here is my code:

let snapProtections = JSON.parse(snapshot.protection);
this.completeMachine.operationModes = snapOperationModes;
        snapProtections.forEach(async prot => {
          this.test.push(await this.protectionDataAcessService.getProtectionAndOperationModesByProtectionId(prot.id));
        });

test is an array of type ProtectionAndOperationModes:

export interface ProtectionAndOperationModes {
    protection: Protection;
    operationModes: OperationMode[];
    image?: EntityImage;
}

This is the getProtectionAndOperationModesByProtectionId function:

public async getProtectionAndOperationModesByProtectionId(protectionId: string): Promise<ProtectionAndOperationModes> {
    const protection = await this.protectionService.getById(protectionId);
    return await this.getOperationModesOfProtection(protection);
  }

private async getOperationModesOfProtection(protection: Protection): Promise<ProtectionAndOperationModes> {
    const availableOperationModes = await this.operationModeService.getByMachineId(protection.machineId);
    const linkedOperationModes = await this.protectionLinkService.getByProtectionId(protection.id);
    const image = await this.imageService.getByEntityId(protection.id);
    return {
      protection: protection,
      operationModes: availableOperationModes.filter(o => linkedOperationModes.find(l => l.operationModeId === o.id)),
      image: image
    };
  }

Any help on how to get the objects into an array?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Okay, so I just jumped to your code and did not fully read that the error you're getting is pushing to a nonexistant array. I'll leave the original since this will be a followup issue :)

Your this.test variable is undefined, hence you cannot push to it. You can go arround the issue by not pushing to it but assigning the variable directly - or by making sure it exists beforehand. In my original answer I also showed a way you can do that (the last line in the code).

Original answer

Your code does work - just not in a way you're expecting it. The pushing happens asynchronously, so you most likely observe it too soon.

To wait until your array is filled, you have to await all of your promises like this:

let snapProtections = JSON.parse(snapshot.protection);
this.completeMachine.operationModes = snapOperationModes;

// protectionModes will contain an array of the resolved promises values
const protectionModes:ProtectionAndOperationModes[] = await Promise.all(
   // map the prots to an array of promises and await that array using promise.all
   snapProtections.map(prot => this.protectionDataAcessService.getProtectionAndOperationModesByProtectionId(prot.id))
);

protectionModes.forEach(mode => this.test.push(mode)); 
// or use spread: 
this.test.push(...protectionModes);
// or just assign to it
this.test = protectionModes;

This way, your data will be filled after this code.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda