Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

229
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda