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

228
Visualizações
Callbacks within forEach()

When uploading a single image i.e., uploadResults only has one object -the following works fine.

When uploading multiple images it doesn't. The image object gets created correctly in the db but the album object has repeat images. For example, if I upload image1 and image2, album.Images should simply be [image1, image2] but instead it will be [image1, image2, image2]. I believe the issue is the timing of the callbacks within the foreach but can't quite pinpoint the issue..

uploadResults.forEach(function(uploadedItem) {
    var image = new Images({
        imageUrl: uploadedItem.url,
    });    
    image.save(function (err, doc) {    
        album.Images.push(doc.id);
        album.save(function(err, doc) {
            //err handling...
        });
     });
 });
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Why are you saving the album on each iteration? Use Promise (probably need a polyfill for all). Use es6-promise:

const Promise = require('es6-promise').Promise;

let promises = [];
uploadResults.forEach(uploadedItem => {
    let promise = new Promise((resolve, reject) => {
        let image = new Images({
            imageUrl: uploadedItem.url,
        });   
        image.save((err, doc) => {
            album.Images.push(doc.id);
            // No saving here
        });
    });
    promises.push(promise);
});

Promise
    .all(promises)
    .then(() => {
        album.save((error, doc) => {
            // rest of code
        });
    });
over 4 years ago · Santiago Trujillo Relatório

0

I've gotten it to work by only running album.save() on the final iteration.

uploadResults.forEach(function(uploadedItem, idx, array) {
    var image = new Images({
        imageUrl: uploadedItem.url,
    });    
    image.save(function (err, doc) {    
        album.Images.push(doc.id);
        if (idx === array.length - 1) {
            album.save(function(err, doc) {
                //err handling...
            });
        }
     });
 });
over 4 years ago · Santiago Trujillo 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