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

247
Visualizações
How to push to an array in an asynchronous operation in JavaScript?

I am trying to push to an array inside a nested forEach loop in JavaScript yet to no avail. I have tried cloning the array and appending to it but doesn't seem to work for me. below is my code. any help would be hugely appreciated. thanks in advance.

const trollImgIds = ["61c25b801957f9eb4f5c2a94", "61c25b801957f9eb4f5c2a95"];
const images:any = [];
trollImgIds.forEach((trollImgId:any) => {
    const imgIds = trollImgId.imgIds;
    imgIds.forEach(async (imgId:any) => {
    const _id = new mongoose.Types.ObjectId(imgId);
    imgGfs.find({ _id: _id }).toArray((err:any, files:any) => {
          if(err){
             console.log(err);
          }
          if(files.length > 0){
              const image:any = [];
              // open download stream and add images to the images array
              const readstream = imgGfs.openDownloadStream(_id);
              // read buffer using stream
              readstream.on('data', (chunk:any) => {
                   image.push(chunk);
              });
              readstream.on('error', () => {
                  console.log('error');
              });
              readstream.on('end', () => {
                 // convert buffer to bufferlist
                 const bufferList = new BufferList(image);
                 // convert the bufferlist to base64 string
                 const base64 = bufferList.toString('base64');
                 // add to images array
                 // console.log("image >>> : ", base64);
                 // clone and add to images array
                 const trollImage = {
                       trollId: trollImgId.id,
                       image: base64
                 }
                 // clone the images array
                 const cloneImages = [...images];
                 // add the troll image to the images array
                 cloneImages.push(trollImage);
                 // set the images array
                  images.push(cloneImages);
            });
         }
      });
  });

});

I was expecting to get an output like:

images >>> :  [
{
    trollId: new ObjectId("61c25b801957f9eb4f5c2a94"),
    image: '/9j/4AAQSkZJRgABAQEAYABgAAD/...'
  }
]

which is the case when I log it inside the second forEach loop however it turns out to be empty outside the loops

about 4 years ago · Santiago Trujillo
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